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

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

8

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

1 Comment

Yes, this is for latest versions (LINQ3) as explained in their JIRA

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.