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

后端 未结 6 1886
清酒与你
清酒与你 2020-12-10 12:37

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

6条回答
  •  甜味超标
    2020-12-10 13:25

    For those using version 2.0 of the MongoDB.Driver, you can make use of the BulkWriteAsync method.

    
    // our example list
    List products = GetProductsFromSomewhere();  
    
    var collection = YourDatabase.GetCollection("products"); 
    
    // initialise write model to hold list of our upsert tasks
    var models = new WriteModel[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(new BsonDocument("aw_product_id", products[i].aw_product_id), bsonDoc) { IsUpsert = true };
    };
    
    await collection.BulkWriteAsync(models); 
    

提交回复
热议问题