如何在Mongo(C#驱动程序)中修改嵌套属性(数组)中的单个元素而又不检索整个文档?
public class Element
{
public int Value {get; set;}
public string Name {get; set;}
}
public class Document
{
public Element [] Elements {get; set;}
}
在示例中,我想查找名称为“ Car”的元素,并在单个查询中将其值设置为4。
答案 0 :(得分:1)
您需要$ positional operator来指定文档级条件和数组级条件,以在特定文档的数组中查找单个嵌套项。在C#中,$
的符号由作为模型数组的索引传递的-1
表示。试试:
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);