How does mongoose determine the number of documents that were changed in an .update()? Does the node-mongodb-native driver return that information? I can't seem to find this in the docs.

有帮助吗?

解决方案

Yes it does:

db.collection('foo').update({},
    {$set:'foo'},
    {multi: true},
    function (err, numberUpdated) {
      console.log(numberUpdated);
    });

If you don't use multi: true the numberUpdated will be always 0 or 1.

Documentation and examples for node-mongodb-native here.

How does it works? When the w option of the update command (called write concern) is greater than or equals to 1 (default to 1) the driver executes the getLastError command, this command returns among other things the number of records affected by the operation.

Example with the mongo repl from another answer in SO:

> db.count.update({x : 1}, {$inc : {x : 1}}, false, true)
> db.runCommand({getLastError : 1})
{
"err" : null,
"updatedExisting" : true,
"n" : 5, //this
"ok" : true
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top