C# mongodb 驱动程序 2.0 - 如何在批量操作中更新插入?

C# mongodb driver 2.0 - How to upsert in a bulk operation?

我从 1.9 迁移到 2.2,reading the documentation 我惊讶地发现在批量操作期间不可能再更新插入,因为操作不允许选项。

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

应该是

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

这项工作是在进行中、有意为之,还是我遗漏了什么?谢谢。

UpdateOneModelIsUpsert 属性 设置为 true 以将更新转换为更新插入。

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

给定 mongo collection

IMongoCollection<T> collection

和可枚举的记录以插入到 T 具有 Id 字段的位置。

IEnumerable<T> records 

此代码段将进行批量更新(过滤条件可能会根据情况更改):

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

这里是基于@Aviko响应的扩展方法

public static BulkWriteResult<T> BulkUpsert<T>(this IMongoCollection<T> collection, IEnumerable<T> records)
    {
        string keyname = "_id";

        #region Get Primary Key Name 
        PropertyInfo[] props = typeof(T).GetProperties();

        foreach (PropertyInfo prop in props)
        {
            object[] attrs = prop.GetCustomAttributes(true);
            foreach (object attr in attrs)
            {
                BsonIdAttribute authAttr = attr as BsonIdAttribute;
                if (authAttr != null)
                {
                    keyname = prop.Name;
                }
            }
        }
        #endregion

        var bulkOps = new List<WriteModel<T>>();


        foreach (var entry in records)
        {
            var filter = Builders<T>.Filter.Eq(keyname, entry.GetType().GetProperty(keyname).GetValue(entry, null));

            var upsertOne = new ReplaceOneModel<T>(filter, entry){ IsUpsert = true };

            bulkOps.Add(upsertOne);
        }

        return collection.BulkWrite(bulkOps);

    }