Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 585
UberFace Avatar asked Sep 26 '18 15:09

UberFace


People also ask

What is Mongo C?

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.

What is a Mongo Driver?

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.


1 Answers

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);
like image 75
mickl Avatar answered Nov 14 '22 21:11

mickl