문제

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