简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM