Search code examples
c#mongodbbatch-processingmongodb-.net-driverbulk

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


I migrated from 1.9 to 2.2 and reading the documentation I was surprised to discover that is not possible to upsert during a bulk operation anymore, since operations don't allow options.

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

Should be

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

Is this work in progress, intended, or I'm missing something? Thank you.


Solution

  • Set the IsUpsert property of the UpdateOneModel to true to turn the update into an upsert.

    var bulkOps = new List<WriteModel<BsonDocument>>();
    // Create and add one or more write models to list
    var upsertOne = new UpdateOneModel<BsonDocument>(filter, update) { IsUpsert = true };
    bulkOps.Add(upsertOne);
    // Write all changes as a batch
    collection.BulkWrite(bulkOps);