【发布时间】:2015-12-31 07:50:29
【问题描述】:
我有以下类型的 mongodb 集合:
public class Entity
{
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public int Field1{ get; set; }
public int Field2{ get; set; }
}
在客户端上,我有一组设置了 Field1 和 Field2 且没有 ID 的实体。
我想根据 Field1 和 Field2 组合在一批中更新它们(认为唯一的“候选”键) - 如果存在这样的组合 - 不做任何事情/更新现有的(它是相同的),如果它不存在 - 插入新实体。
可以通过多次 UpdateAsync 调用轻松完成:
UpdateOptions() { IsUpsert = true }
var filter = new FilterDefinitionBuilder<Enity>().Where(p => p.Field1 == entiy.Field1 && p.Field2 == entity.Field2);
await UpsertAsync(entity, filter);
但这不是很多/批量操作。
我正在查看 API/文档:
- 使用 BulkWriteAsync - 查看答案
- 使用 InsertManyAsync 我看不到如何指定 upsert
- 使用 UpdateManyAsync 其神秘之处在于如何将字段值组合发送到插入/更新
【问题讨论】:
-
看来我需要使用 UpdateOneModel 和为 BulkWriteAsync 设置的 Upsert 属性。我会试试看,可能会回答我的问题。
标签: c# mongodb mongodb-query mongodb-.net-driver