Mongo C# driver update a specific element in a nested array

*爱你&永不变心* 提交于 2019-12-11 04:03:15

问题


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

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


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


来源:https://stackoverflow.com/questions/52521677/mongo-c-sharp-driver-update-a-specific-element-in-a-nested-array

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