Search code examples
c#arraysmongodbmongodb-.net-drivermongodb-csharp-2.0

Update field in array mongodb c# driver


I try to update status field for object from p2l array

var update = Builders<BsonDocument>.Update.Set("p2l.$.status",BsonValue.Create(status))

It seems that code will work fine, but how to implement it with typed builder and set all fields with lambda ? I found a solution by the following link How to update a field in an array's subdocument contained in an array's subdocument in MongoDB using C# driver?

But it suitable only for old version of driver.


Solution

  • You can try something like:

    Builders<Person>.Update.Set(x => x.Pets[-1].Name, "Fluffencutters")
    

    Note -1 index on Pets collection, that means to apply set for all elements.
    I found this solution by exploring UpdateDefinitionBuilderTests.