Mongo C# 驱动程序更新嵌套数组中的特定元素 [英] Mongo C# driver update a specific element in a nested array

查看:48
本文介绍了Mongo C# 驱动程序更新嵌套数组中的特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Mongo(C# 驱动程序)中修改嵌套属性(数组)中的单个元素而不检索整个文档?

How do I modify in Mongo (C# driver) a single element in a nested property (array) without retrieving the whole document?

public class Element
{
    public int Value {get; set;}

    public string Name {get; set;}
}

public class Document
{

     public Element [] Elements {get; set;}
}

在示例中,我想在单个查询中找到名为Car"的元素并将其值设置为 4.

In example I want to find the element with name "Car" and sets its value to 4 in a single query.

推荐答案

您需要 $ 位置运算符,您可以在其中指定文档级条件和数组级条件以在特定文档的数组中查找单个嵌套项.在 C# 中,$ 符号由作为模型数组索引传递的 -1 表示.试试:

You need $ positional operator where you can specify document-level condition and array-level condition to find single nested item in an array of particular document. In C# $ sign is represented by -1 passed as an index of your model array. Try:

var col = mydb.GetCollection<Document>("collectionName");
var id = new ObjectId("5babaaf5509f6d342da5abaa");
var elementName = "Car";
var newValue = 2;

var filterBuilder = Builders<Document>.Filter;
var filter = filterBuilder.Eq(x => x.Id, id) &
    filterBuilder.ElemMatch(doc => doc.Elements, el => el.Name == elementName);

var updateBuilder = Builders<Document>.Update;
var update = updateBuilder.Set(doc => doc.Elements[-1].Value, newValue);

Col.UpdateOne(filter, update);

这篇关于Mongo C# 驱动程序更新嵌套数组中的特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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