mongodb驱动程序c#更新嵌套对象数组中的一个字段

发布于 2025-02-01 16:53:06 字数 459 浏览 3 评论 0原文

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?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

朮生 2025-02-08 16:53:06
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/main/dotnet/01%20-20-%20Begin/10%20%20-%20updatenestedarray.cs

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文