1

Salam (means hello) :)

I'm running mongodb 2.4.8 and Mongo DB Native NodeJS Driver. when I use the following function, only first document that matched query updates. how can I update all matching documents?

function update(coll, query, update, callback){
    var options = options || {};
    MongoClient.connect('mongodb://127.0.0.1:27017/dbName', function(error, db) {
        if(error){
            return console.dir(error);
        }
        db.collection(coll).update(query, update, {w:1}, function(error, result) {
            callback(error, result);
        });
    });
}

I installed my mongodb driver via npm install mongodb command, which installs version 1.3.23, does this driver version support multi update? if not, how can I install a newer version of driver supports multi update?

2 Answers 2

3

You need to set the multi option in your update call to update all matching docs instead of just the first one:

db.collection(coll).update(query, update, {w:1, multi: true}, callback);
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, I also found another document for update function which doesn't need neither callback function nor {w:1}, can you explain their difference?
@NasserTorabzade That doc is for the Mongo shell, not the node.js driver. But you likely don't need w:1 in your code, either.
3

You can call updateMany to achieve this:

db.collection(coll).updateMany(query, update, callback);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.