简体   繁体   English

如何在MongoDb中简单地执行更新/替换许多文档的操作

[英]How to simply perform a update/replace many documents operation in MongoDb

This is perhaps one of the most common and basic database operations you can perform. 这也许是您可以执行的最常见和最基本的数据库操作之一。 However, how you perform this operation in MongoDb, is elusive. 但是,如何在MongoDb中执行此操作是难以捉摸的。

There's a UpdateManyAsync method in the C# driver. C#驱动程序中有一个UpdateManyAsync方法。 But all I can find for it is examples like; 但是我能找到的只是像这样的例子。

The following operation updates all documents where violations are greater than 4 and $set a flag for review: 以下操作将更新所有违规大于4的文档,并为标记设置$进行审核:

try {
   db.restaurant.updateMany(
      { violations: { $gt: 4 } },
      { $set: { "Review" : true } }
   );
} catch (e) {
   print(e);
}

Frankly I don't know how you guys build your applications but our organization will never embed domain logic like how many violations constitutes a review in our database querying logic. 坦白地说,我不知道你们是如何构建应用程序的,但是我们组织永远不会像在数据库查询逻辑中嵌入多少次违规那样嵌入域逻辑。 Like all the examples I can find for this operation do. 像我可以找到的用于此操作的所有示例一样。

It seems at best that our option is to use some sort of bulk api for this, which seems unnecessary for such a simple operation. 看来最好的选择是为此使用某种批量api,对于这样一个简单的操作来说似乎没有必要。 Making the bulk api perform a thousand separate replaces seems ineffective to me, but I might be wrong here? 使批量api执行一千次替换对我来说似乎无效,但是我在这里可能错了?

In other storage technologies and more mature API's all the code necessary to perform this operation is (example Entity framework); 在其他存储技术和更成熟的API中,执行此操作所需的所有代码为(示例Entity框架);

db.UpdateRange(stocks);
await db.SaveChangesAsync();

Is this tracked as a feature request for the Mongo project somewhere? 是否在某个地方对Mongo项目的功能请求进行了跟踪?

Bulk API can handle it see code below: 批量API可以处理它,请参见以下代码:

            var updates = new List<WriteModel<CosmosDoc>>();
            foreach (var doc in docs)
            {
                updates.Add(new ReplaceOneModel<CosmosDoc>(doc.Id, doc));
            }
            await MongoDb.DocsCollection.BulkWriteAsync(updates, new BulkWriteOptions() { IsOrdered = false });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM