Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get number of updated documents mongo

Is there a function in mongo to return the number of documents that were updated in an update statement?

I have tried to use count() but apparently the update statement only returns true or false so i think I'm getting the count of a string.

Thanks

like image 714
K2xL Avatar asked Nov 15 '11 20:11

K2xL


2 Answers

Use the getLastError command to get information about the result of your operation.

I don't know the ruby driver, but most drivers automatically do this in 'safe mode'. In safe mode, each write will examine the result of getLastError to make sure the write was successful. The update operation should return an object that looks like the JSON object further down, and it includes the number of updated documents (n). You can fine-tune the safe mode settings, but be warned that the default mode is "fire and forget", so safe mode is a good idea for many use cases.

In the shell,

> db.customers.update({}, {$set : {"Test" : "13232"}}, true, true);
> db.runCommand( "getlasterror" )
{
    "updatedExisting" : true,
    "n" : 3,
    "connectionId" : 18,
    "err" : null,
    "ok" : 1
}

Here, I updated n = 3 documents. Note that by default, update operations in mongodb only apply to the first matched document. In the shell, the fourth parameter is used to indicate we want to update multiple documents.

like image 95
mnemosyn Avatar answered Nov 03 '22 23:11

mnemosyn


For future reference as of the latest version of mongoDB, you can save the result of the update command and look for the property modifiedCount. Note that if the update operation results in no change to the document, such as setting the value of the field to its current value, it may be less than the number of documents that were matched in the query.

For example (in JS):

var updateResult = await collection.updateOne( .... )

if(updateResult.modifiedCount < 1)  throw new Error("No docs updated");

There are also two fields result.n and result.nModified in the response object that tell you the number of documents matched, and the number updated, respectively. Here's a portion of the response object that mongoDB returns

result: {
    n: 1,
    nModified: 1,
    ...
  },
...
modifiedCount: 1

More info here: https://docs.mongodb.com/manual/reference/command/update/

like image 1
emich Avatar answered Nov 03 '22 23:11

emich