簡體   English   中英

MongoDB 驅動程序 C# 更新嵌套對象數組中的單個字段

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

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

}

給定地區名稱、州名稱、國家 ID 和新人口,我如何更新單個地區的人口。 使用 LinQ 和 MongoDBDriver?

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

此處的完整示例https://github.com/iso8859/learn-mongodb-by-example/blob/main/dotnet/01%20-%20Begin/10%20-%20UpdateNestedArray.cs

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM