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.
A Cross Platform MongoDB Client Library for C. The MongoDB C Driver, also known as “libmongoc”, is a library for using MongoDB from C applications, and for writing MongoDB drivers in higher-level languages. It depends on libbson to generate and parse BSON documents, the native data format of MongoDB.
The official MongoDB Node. js driver allows Node. js applications to connect to MongoDB and work with data. The driver features an asynchronous API which allows you to interact with MongoDB using Promises or via traditional callbacks.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With