1

为什么getLastError显示没有更新文档?

> 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正在返回n: 0,即使文档已明确更新。它也缺少该updatedExisting领域。我在一个示例 MongoHQ 数据库上远程运行它。

针对我的本地 MongoDB 实例运行,getLastError正确返回:

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

1 回答 1

2

这可能是连接重用的问题,也可能是外壳行为。getLastError (GLE) 调用仅返回在执行 GLE 调用的连接上发生的最后一个操作的状态。

但是,当你使用 shell 时,它会在每次写操作后自动调用 GLE,所以你通常会得到一个 null 结果,因为 GLE 已经被调用了。尝试调用getPrevError()- 看看它是否返回您的预期。

MongoDB 驱动程序通过确保在将连接返回到池之前调用 GLE 并作为操作的结果(或错误)返回来避免此类问题,从而解决此问题。

于 2012-11-08T10:15:54.603 回答