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

时间:2016-02-28 19:53:49

标签: c# mongodb batch-processing mongodb-.net-driver bulk

我从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);

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

3 个答案:

答案 0 :(得分:17)

UpdateOneModel的{​​{3}}属性设置为true,将更新转换为upsert。

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

答案 1 :(得分:4)

给出mongo集合

IMongoCollection<T> collection

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

IEnumerable<T> records 

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

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);

答案 2 :(得分:1)

这是基于@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);

    }