更新 MongoDB 集合中所有文档中的元素
我正在运行以下查询,目的是更新集合中所有现有文档中的单个元素。我基本上试图将它们的值清除为“0”。
这是代码:
MongoCollection collection = db.GetCollection(DataAccessConfiguration.Settings.CollectionName);
var query = Query.Exists("ElementName", true);
var update = Update.Set("ElementName", "0");
collection.Update(query, update);
它只更新单个文档。
如何一次更新所有元素?
I am running the following query with the purpose of updating a single element in all the existing documents in the collection. I am basically trying to clear their value to "0".
Here is the code:
MongoCollection collection = db.GetCollection(DataAccessConfiguration.Settings.CollectionName);
var query = Query.Exists("ElementName", true);
var update = Update.Set("ElementName", "0");
collection.Update(query, update);
It only updates a single document.
How can I update all elements at once?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
默认情况下,MongoDB 中的更新会影响 0 或 1 个文档(仅当查询说明符不匹配任何内容时才影响 0)。要更新所有文档,您需要传递
UpdateFlags.Multi
作为第三个参数Update
。Update
还有一个 4 参数版本,它接受“安全模式”标志作为第四个参数。(安全模式将 getLastError 命令与更新捆绑在一起,并使驱动程序等待,直到服务器确认写入已成功。安全模式有多种选项,可以在以下情况下等待多个服务器的确认:您正在使用副本集,它只会等待一段时间,然后返回错误,等等)。
另请务必查看 C# 驱动程序文档以获取有关 API 的详细信息。
Updates in MongoDB affect 0 or 1 documents by default (0 only if the query specifier doesn't match anything). To update all documents, you need to pass
UpdateFlags.Multi
as the third argumentUpdate
. There is also a 4-argument version ofUpdate
which accepts the "safe mode" flag as the fourth argument.(Safe mode bundles a
getLastError
command with the update, and causes the driver to wait until the server acknowledges that the write has succeeded. There are various options to safe mode that will wait for acknowledgement from multiple servers if you are using a replica set, that will wait only for a certain period of time and then return with an error, etc).Also be sure to see the C# driver documentation for details on the API.