如何使用C#实现MongoDb中使用多个过滤器的批量更新?

ryoqjall  于 2022-12-12  发布在  Go
关注(0)|答案(1)|浏览(156)

我有一个EmployeeDetails集合。该集合有4个字段。我有一个包含前三个字段的筛选器。如果找到匹配的数据,我希望更新($set),否则插入(.SetOnInsert {upsert});然而是散装的。

EmpName:
EmpCompany:
EmpDesignation:
EmpSalary:

我想根据其他字段更新EmpSalary。同时,筛选数据将被批量发送。是否可以这样做w/o foreach循环。
我试过以下代码:

foreach( var filterData in filterDataArrayList)
{
         var loadData = Builders<EmployeeModel>.Update
         .SetOnInsert(x=>x.EmpSalary , Salary)
         .SetOnInsert(x=>x.EmpName , Name)
         .SetOnInsert(x=>x.EmpCompany , Company)
         .SetOnInsert(x=>x.EmpDesignation , Designation)

var insertResult = await collection.UpdateOneAsync(
x=>x.EmpName == filterData.Name, x=>x.EmpCompany=filterData.Company, x=>x.EmpDesignation = filterData.Designation  ), loadData,
new UpdateOptions() {IsUpsert=true});

if(loadData.upsertId==null && loadData.matchedCount==1)
   {
      var updateData = Builders<EmployeeModel>.Update
         .Set(x=>x.EmpSalary , Salary)
      
      var updateResult = await collection.UpdateOneAsync(
      x=>x.EmpName == filterData.Name, x.EmpCompany=filterData.Company, x.EmpDesignation =filterData.Designation  ), updateData)

   }

这段代码运行良好。我想消除过滤器数据的foreach循环。这可能吗?

0x6upsns

0x6upsns1#

试试这个:

var client = new MongoClient();
        var db = client.GetDatabase("d");
        var coll = db.GetCollection<BsonDocument>("c");

        coll.BulkWrite(new[]
        {
            new UpdateOneModel<BsonDocument>(
                "{ whatever1 : 1 }",
                new UpdateDefinitionBuilder<BsonDocument>()
                    .SetOnInsert("field1", 1)
                    .SetOnInsert("field2", 2)),
            new UpdateOneModel<BsonDocument>(
                "{ whatever2 : 1 }",
                new UpdateDefinitionBuilder<BsonDocument>()
                    .SetOnInsert("field21", 1)
                    .SetOnInsert("field22", 2))
                {
                    IsUpsert = true
                }
        });

这个例子只是为了说明如何完成它,你也可以使用一种类型化的/更复杂的方式,就像你的例子一样

相关问题