I am using MongoDB 2, and I want to update multiple documents and upsert a value like processed:true
into the collection. But MongoDB c# api only allows us to either Update Multiple Records or Upsert a single record.
How to solve this problem using the C# api?
Upsert is a combination of insert and update (inSERT + UPdate = upsert). We can use the upsert with different update methods, i.e., update, findAndModify, and replaceOne. Here in MongoDB, the upsert option is a Boolean value. Suppose the value is true and the documents match the specified query filter.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With