Pregunta

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.

¿Fue útil?

Solución

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
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top