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

微笑、不失礼 提交于 2019-12-17 19:34:38

问题


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?


回答1:


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



回答2:


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




回答3:


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



回答4:


Try first removing all items to be inserted from the collection, and then calling insert:

        var search = [];
        arrayToInsert.forEach(function(v, k) {
            search.push(v.hash); // my unique key is hash. you could use _id or whatever
        })
        collection.remove({
            'hash' : {
                $in : search
            }
        }, function(e, docs) {

            collection.insert(arrayToInsert, function(e, docs) {
                if (e) {
                    console.log("data failed to update ", e);
                }
                else {
                    console.log("data updated ");
                }
            });
        })



回答5:


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.

var flags = UpdateFlags.Upsert | UpdateFlags.Multi;

You 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



来源:https://stackoverflow.com/questions/7934768/how-to-update-and-upsert-multiple-documents-in-mongodb-using-c-sharp-drivers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!