1

I have multiple MongoDB documents like this:

{
    "_id":"abcde",
    "Students":[
        {"Name":"John","IsNew":true},
        {"Name":"Steve","IsNew":true}
    ],
}

{
    "_id":"fghij",
    "Students":[
        {"Name":"Ron","IsNew":true},
        {"Name":"Mike","IsNew":true}
    ],
}

How to update the IsNew field to false for all students for every document using C# driver?

1
  • Can you show what you have tried? Commented Feb 4, 2019 at 11:35

1 Answer 1

3

You can use UpdateMany method from MongoDB C# driver with the positional all operator:

var filter = Builders<YourModel>.Filter.Exists(x => x.Students);

FieldDefinition<YourModel, bool> field = "Students.$[].IsNew";
var update = Builders<YourModel>.Update.Set(field, false);

Col.UpdateMany(filter, update);

EDIT: you can use .Exists() as a filter to make sure that Students array is present in all the documents that are being updated

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer. It worked but students array is not present in all the documents. If students array is not in the document, then compiler throws error: Students must exist in the document.
@nff modified my answer
Thanks @mickl .Is there any way we can filter the documents such that it only updates the elements having IsNew flag as true?. With the current approach, filter contains all the documents having Students list.
@nff sorry for the delay, please open new question if you still need help since it significantly changes the scope of current question

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.