C# mongodb driver 2.0 - How to upsert in a bulk operation?
Set the IsUpsert
property of the UpdateOneModel
to true to turn the update into an upsert.
var upsertOne = new UpdateOneModel<BsonDocument>(filter, update) { IsUpsert = true };
bulkOps.Add(upsertOne);
collection.BulkWrite(bulkOps);
given mongo collection
IMongoCollection<T> collection
and enumerable of records to insert where T has Id field.
IEnumerable<T> records
this snippet will do a bulk upsert (the filter condition may be changed according to the situation):
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);