使用数组更新运算符$ [< identifier>]的以下查询的MongoDB C#驱动程序等效项是什么 [英] What would be the MongoDB C# driver equivalent of the following query using the array update operator $[<identifier>]

查看:64
本文介绍了使用数组更新运算符$ [< identifier>]的以下查询的MongoDB C#驱动程序等效项是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

给出以下集合

{
   "_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 }
   ]
}

并查询

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

如何使用C#驱动程序执行相同的查询?目前,我只是使用db.RunCommand对数据库运行查询,因为我看不到使用当前驱动程序将其转换为C#的方法.

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.

推荐答案

您可以在c#以下尝试使用BsonDocument和json字符串选项.没有linq选项.

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

这篇关于使用数组更新运算符$ [&lt; identifier&gt;]的以下查询的MongoDB C#驱动程序等效项是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆