get number of updated documents mongo
Asked Answered
C

2

8

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

Cyril answered 15/11, 2011 at 20:12 Comment(0)
A
9

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.

Abdullah answered 15/11, 2011 at 20:31 Comment(0)
C
1

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/

Caress answered 13/8, 2020 at 23:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.