What would be the MongoDB C# driver equivalent of the following query using the array update operator $[<identifier>]

China☆狼群 提交于 2019-12-20 06:28:15

问题


From https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/#up.S[%3Cidentifier%3E]

Given the following collection

{
   "_id" : 1,
   "grades" : [
      { "grade" : 80, "mean" : 75, "std" : 6 },
      { "grade" : 85, "mean" : 90, "std" : 4 },
      { "grade" : 85, "mean" : 85, "std" : 6 }
   ]
}
{
   "_id" : 2,
   "grades" : [
      { "grade" : 90, "mean" : 75, "std" : 6 },
      { "grade" : 87, "mean" : 90, "std" : 3 },
      { "grade" : 85, "mean" : 85, "std" : 4 }
   ]
}

and query

db.students2.update(
   { },
   { $set: { "grades.$[elem].mean" : 100 } },
   {
     multi: true,
     arrayFilters: [ { "elem.grade": { $gte: 85 } } ]
   }
)

How would I do this same query using the C# driver? At the moment I'm just running the query against the database using db.RunCommand as I couldn't see a way to convert this to C# with the current driver.


回答1:


You can try below c# using both BsonDocument and json string option. There is no linq option.

var filter = Builders<BsonDocument>.Filter.Empty;
var update = Builders<BsonDocument>.Update.Set("grades.$[elem].mean", 100);
var arrayFilter = new BsonDocumentArrayFilterDefinition<BsonDocument>(new BsonDocument("elem.grade", new BsonDocument("$gte", 85)));
var arrayFilter = new JsonArrayFilterDefinition<BsonDocument>("{ \"elem.grade\": { $gte: 85 } }");
var arrayFilters = new List<ArrayFilterDefinition> { arrayFilter };
var updateOptions = new UpdateOptions();
updateOptions.ArrayFilters = arrayFilters;
var result = collection.UpdateOne(filter, update, updateOptions);


来源:https://stackoverflow.com/questions/48876880/what-would-be-the-mongodb-c-sharp-driver-equivalent-of-the-following-query-using

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