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

Nitin Agarwal picture Nitin Agarwal · Oct 28, 2011 · Viewed 28.1k times · Source

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?

Answer

PUG picture PUG · Dec 2, 2014

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();