MongoDB Driver C# Update a single field in Nested Array of Objects

Viewed 40
public class Country
{
    public string Id { get; set; }
    public string Name { get; set; }
    public List<State> States { get; set; }
}

public class State
{

    public string Name { get; set; }
    public List<District> Districts { get; set; }
}

public class District
{

    public string Name { get; set; }
    public string Population { get; set; }

}

How can I Update Population of a single District, given District Name ,State Name, Country Id and New Population. Using LinQ and MongoDBDriver?

1 Answers
var update = Builders<Country>.Update.Set(_ => _.States[0].Districts[-1].Population, "5,000,000");
Console.WriteLine(update.Render(collection.DocumentSerializer, collection.Settings.SerializerRegistry));
// { "$set" : { "States.0.Districts.$.Population" : "5,000,000" } }

await collection.FindOneAndUpdateAsync<Country>(   // <= you must tell C# this is Country to have linq syntax available
    _ => _.Id == "USA" && _.States.Any(s => s.Name == "California") && _.States.Any(s => s.Districts.Any(d => d.Name == "Los Angeles")),
    update
    );

Full example here https://github.com/iso8859/learn-mongodb-by-example/blob/main/dotnet/01%20-%20Begin/10%20-%20UpdateNestedArray.cs

Related