MongoDb官方C#驱动程序批量更新

10
我可以帮您通过使用新的C# MongoDb驱动程序中的IMongoCollection接口重写下面的旧代码,请看以下内容:

如何通过使用新的C# MongoDb驱动程序中的IMongoCollection接口来重写以下旧代码:

var bulk = dbCollection.InitializeUnorderedBulkOperation();
foreach (var profile in profiles)
{
   bulk.Find(Query.EQ("_id",profile.ID)).Upsert().Update(Update.Set("isDeleted", true));  
}

bulk.Execute();

我知道如何使用Builder机制创建Update操作,但如何执行批量更新操作呢?

2个回答

13
MongoDB.Driver有UpdateManyAsync方法。
var filter = Builders<Profile>.Filter.In(x => x.Id, profiles.Select(x => x.Id));
var update = Builders<Profile>.Update.Set(x => x.IsDeleted, true);
await collection.UpdateManyAsync(filter, update);

6
很高兴你涵盖了操作的必要事项,但这并没有回答原问题。解决方案在这里:https://dev59.com/F1sV5IYBdhLWcg3w4iE_#35688613。 - Adrian Lopez

0

在新版本的MongoDB.Driver中可以设置标志

var query = Query<Profile>.In(p => p.ID, profiles.Select(x => x.Id));
var update = Update<Profile>.Set(p => p.IsDeleted, true);
Collection.Update(query, update, UpdateFlags.Multi);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接