获取更新文档的数量 mongo
mongo 中是否有函数可以返回更新语句中更新的文档数量?
我尝试使用 count()
但显然更新语句只返回 true 或 false,所以我认为我正在获取字符串的计数。
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
getLastError
命令获取有关操作结果的信息。我不知道 ruby 驱动程序,但大多数驱动程序会自动在“安全模式”下执行此操作。在安全模式下,每次写入都会检查
getLastError
的结果以确保写入成功。更新操作应该返回一个类似于 JSON 对象的对象,并且它包含更新文档的数量 (n
)。您可以微调安全模式设置,但请注意,默认模式是“即发即忘”,因此安全模式对于许多用例来说是一个好主意。在 shell 中,
我在这里更新了
n = 3
文档。请注意,默认情况下,mongodb 中的更新操作仅适用于第一个匹配的文档。在shell中,第四个参数用于指示我们要更新多个文档。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,
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.为了将来参考最新版本的 mongoDB,您可以保存更新命令的结果并查找属性
modifiedCount
。请注意,如果更新操作不会导致文档发生任何更改,例如将字段的值设置为其当前值,则它可能会小于查询中匹配的文档数。例如(在 JS 中):
响应对象中还有两个字段
result.n
和result.nModified
告诉您匹配的文档数量和更新的数量, 分别。以下是 mongoDB 返回的响应对象的一部分更多信息:https://docs .mongodb.com/manual/reference/command/update/
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):
There are also two fields
result.n
andresult.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 returnsMore info here: https://docs.mongodb.com/manual/reference/command/update/