How to update and upsert multiple documents in MongoDB using C# Drivers
After Mongo 2.6
you can do Bulk Updates/Upserts. Example below does bulk update using c#
driver.
MongoCollection<foo> collection = database.GetCollection<foo>(collectionName);
var bulk = collection.InitializeUnorderedBulkOperation();
foreach (FooDoc fooDoc in fooDocsList)
{
var update = new UpdateDocument { {fooDoc.ToBsonDocument() } };
bulk.Find(Query.EQ("_id", fooDoc.Id)).Upsert().UpdateOne(update);
}
BulkWriteResult bwr = bulk.Execute();
You cannot do it in one statement.
You have two options
1) loop over all the objects and do upserts
2) figure out which objects have to get updated and which have to be inserted then do a batch insert and a multi update
For those using version 2.0 of the MongoDB.Driver, you can make use of the BulkWriteAsync method.
<!-- language: c# -->
// our example list
List<Products> products = GetProductsFromSomewhere();
var collection = YourDatabase.GetCollection<BsonDocument>("products");
// initialise write model to hold list of our upsert tasks
var models = new WriteModel<BsonDocument>[products.Count];
// use ReplaceOneModel with property IsUpsert set to true to upsert whole documents
for (var i = 0; i < products.Count; i++){
var bsonDoc = products[i].ToBsonDocument();
models[i] = new ReplaceOneModel<BsonDocument>(new BsonDocument("aw_product_id", products[i].aw_product_id), bsonDoc) { IsUpsert = true };
};
await collection.BulkWriteAsync(models);