更新 MongoDB 集合中所有文档中的元素

发布于 2024-12-23 05:23:00 字数 373 浏览 4 评论 0原文

我正在运行以下查询,目的是更新集合中所有现有文档中的单个元素。我基本上试图将它们的值清除为“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迟月 2024-12-30 05:23:00

默认情况下,MongoDB 中的更新会影响 0 或 1 个文档(仅当查询说明符不匹配任何内容时才影响 0)。要更新所有文档,您需要传递 UpdateFlags.Multi 作为第三个参数 UpdateUpdate 还有一个 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 argument Update. There is also a 4-argument version of Update 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文