Question

Why does getLastError show that no docs were updated when it was?

> db.contacts.find()
{ "_id" : ObjectId("509b60e7c546b6dc73f57877"), "name" : "mike" }
> db.contacts.update({}, {name: 'peter'})
> db.runCommand({getLastError: 1})
{ "n" : 0, "connectionId" : 3188, "err" : null, "ok" : 1 }
> db.contacts.find()
{ "_id" : ObjectId("509b60e7c546b6dc73f57877"), "name" : "peter" }

getLastError is returning n: 0, even though a document was clearly updated. It's also missing the updatedExisting field. I'm running this remotely on a sample MongoHQ database.

Run against my local MongoDB instance, getLastError correctly returns this:

> db.runCommand({getLastError: 1})
{
    "updatedExisting" : true,
    "n" : 1,
    "connectionId" : 1,
    "err" : null,
    "ok" : 1
}
Was it helpful?

Solution

This might be a problem with connection re-use or it could be the shell behavior. The getLastError (GLE) call just returns the status of the last operation to happen on the connection that executes the GLE call.

However, when you are using the shell, it automatically calls GLE after every write operation, so you will usually get a null result because GLE has already been called. Try calling getPrevError() instead - see if that returns what you expected.

The MongoDB drivers take care of this by making sure that GLE is called before a connection is returned to the pool and that is returned as the result (or error) for an operation to avoid this kind of problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top