C#mongodb驱动2.0 – 如何在批量操作中进行upsert?

我从1.9迁移到2.2并阅读文档我很惊讶地发现在批量操作期间不可能进行升级,因为操作不允许选项。

bulkOps.Add(new UpdateOneModel(filter, update)); collection.BulkWrite(bulkOps); 

应该

 options.isUpsert = true; bulkOps.Add(new UpdateOneModel(filter, update, options)); collection.BulkWrite(bulkOps); 

这项工作正在进行中,有意或者我遗漏了什么? 谢谢。

IsUpsert属性设置为true可将更新转换为upsert。

 var upsertOne = new UpdateOneModel(filter, update) { IsUpsert = true }; bulkOps.Add(upsertOne); collection.BulkWrite(bulkOps); 

给予mongocollections

 IMongoCollection collection 

和可插入的记录,其中T具有Id字段。

 IEnumerable records 

这个片段会进行批量upsert(过滤条件可能会根据情况改变):

 var bulkOps = new List>(); foreach (var record in records) { var upsertOne = new ReplaceOneModel( Builders.Filter.Where(x => x.Id == record.Id), record) { IsUpsert = true }; bulkOps.Add(upsertOne); } collection.BulkWrite(bulkOps);