Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update and upsert multiple documents in MongoDB using C# Drivers

Tags:

mongodb

upsert

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?

like image 830
Nitin Agarwal Avatar asked Oct 28 '11 20:10

Nitin Agarwal


People also ask

What is the difference between update and Upsert in MongoDB?

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.


2 Answers

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();
like image 93
PUG Avatar answered Oct 26 '22 22:10

PUG


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

like image 27
jeffsaracco Avatar answered Oct 27 '22 00:10

jeffsaracco