Home:ALL Converter>How to update and upsert multiple documents in MongoDB using C# Drivers

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

Ask Time:2011-10-29T04:49:02         Author:Nitin Agarwal

Json Formatter

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?

Author:Nitin Agarwal,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/7934768/how-to-update-and-upsert-multiple-documents-in-mongodb-using-c-sharp-drivers
Joey :

For those using version 2.0 of the MongoDB.Driver, you can make use of the BulkWriteAsync method. \n\n<!-- language: c# -->\n// our example list\nList<Products> products = GetProductsFromSomewhere(); \n\nvar collection = YourDatabase.GetCollection<BsonDocument>(\"products\"); \n\n// initialise write model to hold list of our upsert tasks\nvar models = new WriteModel<BsonDocument>[products.Count];\n\n// use ReplaceOneModel with property IsUpsert set to true to upsert whole documents\nfor (var i = 0; i < products.Count; i++){\n var bsonDoc = products[i].ToBsonDocument();\n models[i] = new ReplaceOneModel<BsonDocument>(new BsonDocument(\"aw_product_id\", products[i].aw_product_id), bsonDoc) { IsUpsert = true };\n};\n\nawait collection.BulkWriteAsync(models); \n",
2015-08-24T21:10:12
Henry :

Try first removing all items to be inserted from the collection, and then calling insert:\n\n var search = [];\n arrayToInsert.forEach(function(v, k) {\n search.push(v.hash); // my unique key is hash. you could use _id or whatever\n })\n collection.remove({\n 'hash' : {\n $in : search\n }\n }, function(e, docs) {\n\n collection.insert(arrayToInsert, function(e, docs) {\n if (e) {\n console.log(\"data failed to update \", e);\n }\n else {\n console.log(\"data updated \");\n }\n });\n })\n",
2014-03-22T23:49:57
Craig Wilson :

UpdateFlags is an enum in the C# driver that will let you specify both at once. Just like any other flags enum, you do this by bit \"or\"ing.\n\nvar flags = UpdateFlags.Upsert | UpdateFlags.Multi;\n\n\nYou can read the docs on enums here (http://msdn.microsoft.com/en-us/library/cc138362.aspx) paying special attention to the section on Enumeration Types as Bit Flags",
2013-01-16T14:29:26
Jason Mullings :

Working with [email protected] - try initializeUnorderedBulkOp():\n\nexport const InfoFunc = (Infos: Infos[]) => {\n\n const bulk = InfoResult.collection.initializeUnorderedBulkOp();\n Infos.forEach((info: Infos) => bulk.find({ \"Id\": info.Id}).upsert().updateOne(info));\n bulk.execute();\n}\n",
2020-04-16T14:44:09
PUG :

After Mongo 2.6 you can do Bulk Updates/Upserts. Example below does bulk update using c# driver.\n\nMongoCollection<foo> collection = database.GetCollection<foo>(collectionName);\n var bulk = collection.InitializeUnorderedBulkOperation();\n foreach (FooDoc fooDoc in fooDocsList)\n {\n var update = new UpdateDocument { {fooDoc.ToBsonDocument() } };\n bulk.Find(Query.EQ(\"_id\", fooDoc.Id)).Upsert().UpdateOne(update);\n }\n BulkWriteResult bwr = bulk.Execute();\n",
2014-12-02T20:34:20
jeffsaracco :

You cannot do it in one statement.\n\nYou have two options \n\n1) loop over all the objects and do upserts\n\n2) figure out which objects have to get updated and which have to be inserted then do a batch insert and a multi update",
2011-10-28T22:48:28
yy