How to use $ positional operator in MongoDB C# driver version 2
Asked Answered
M

2

9

I need to update a field of one element from array sub document of a document.

MongoDB have the $ positional operator to do this. But in MongoDB C# driver version 2 it seems that there is no support for this operator.

How can I achieve this?

Documents:

{ "_id" : 1, "grades" : [ 80, 85, 90 ] }
{ "_id" : 2, "grades" : [ 88, 90, 92 ] }
{ "_id" : 3, "grades" : [ 85, 100, 90 ] }

Expected query:

db.students.update(
     { _id: 1, grades: 80 },
     { $set: { "grades.$" : 82 } }
   )
Meuse answered 22/2, 2017 at 16:19 Comment(0)
W
15

You can try something like this.

var builder = Builders<Student>.Filter;
var filter = builder.Eq(student=> student.Id, 1) & builder.ElemMatch(student => student.Grades, x => x == 80);

var builder = Builders<Student>.Update;
var update = builder.Set(student => student.Grades[-1], 82);

var result = collection.UpdateOne(filter, update);
Whisker answered 22/2, 2017 at 19:34 Comment(0)
R
7

I know this is a very late answer, but if anyone else comes across this I tried s7vr's answer with the -1 index and got an exception that pointed to Mongo's FirstMatchingElement method, and that solved my problem.

So it would be the same filter as in that answer, but replacing update with something like

var update = Builders<Student>.Update.Set(student => student.Grades.FirstMatchingElement(), 82);
Rosol answered 11/9, 2023 at 13:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.