Reputation: 69
I'm using mongoDB (3.4) with a node.js driver and I'm trying to update a field in all documents contained within "items_collection". I've tried a couple of different approaches but I can't seem to find a solution which correctly updates ALL documents. Below is the code I've currently got:
var cursor = db.collection('items_collection').find();
cursor.on("end", function() {
console.log("Finished. Closing db...");
db.close();
});
cursor.on("err", function() {
console.dir("Error on:" + err);
throw err;
});
cursor.on("data", function(doc) {
cursor.pause();
var newTitle = getTitleFromDescription(doc.description);
db.collection('items_collection').update({_id: doc._id}, {$set:{title: newTitle}}, {multi:true});
cursor.resume();
});
This seems reasonably sane to me, however it's only ever the first document which gets its title updated to "test_title". I must be missing something obvious here right?
Thanks.
Upvotes: 0
Views: 321
Reputation: 2045
Use update instead of save and use multi : true
for multiple document udpates:
db.collectionname.update( {}, { $set:{ title : "newvalue" } }, { multi : true } );
All updates in MongoDB are, by default, singular. you must add a multi : true
cursor.on("data", function(doc) {
cursor.pause();
var newTitle = getTitleFromDescription(doc.description);
console.log(doc._id);
console.log(newTitle);
db.collection('items_collection').update({_id: doc._id}, {$set:{title: newTitle}}, {multi:true}).then(function(response){
console.log(response);
console.log('++++++++++++++++++');
cursor.resume();
});
});
Upvotes: 2
Reputation: 2640
You can easily do this with a multi-update. Assuming you want to update every document in your collection, you would do:
db.collection("items_collection").update({},{$set:{title: "test_title"},{multi:true} );
The docs explain this clearly here.
Also note that you must update operator expressions for multi-updates. If you were updating a single document, the second parameter to the update
method can be a plain object of field:value
, but a multi-update has to use an update operator like $set
in the example above.
Upvotes: 0