【问题标题】:Mongodb fluent aggregation and grouping in C#C# 中的 Mongodb 流式聚合和分组
【发布时间】:2021-12-31 22:09:24
【问题描述】:

我的 .Net / C# 应用程序在 Mongodb 中存储了一些信息。 Mongodb文档在C#中对应的结构如下:

public class GlobalInfo
{
    public ObjectId Id { get; set; }
    public string Country { get; set; }
    public string City { get; set; }
    public int Population { get; set; }
}

我想从 Mongodb 文档中提取包含所有国家/地区的 List<CountryInfo>,或者最终提取为 Dictionary<string, List<CityInfo>>(国家名称将是字典键),基于以下类:

public class CountryInfo
{
    public string Name { get; set; }
    public List<CityInfo> Cities { get; set; }
}

public class CityInfo
{
    public string Name { get; set; }
    public int Population { get; set; }
}

我找到了一些关于类似功能的 c# 示例,这些示例是在 Mongodb C# 驱动程序的 Aggregate()Match()Group() 方法的帮助下实现的。我不确定如何在我的示例中使用它们。

基本上,我需要将带有 Mongodb db 文档的平面列表转换为带有嵌套列表或字典的分层模型。有人可以帮忙提供一些样品吗?

【问题讨论】:

    标签: c# mongodb aggregate grouping fluent


    【解决方案1】:

    您可以使用group 关键字并按国家/地区对实体进行分组,然后在select 中构造一个对象CountryInfo,您可以使用组中的Key 值设置Name,@ 987654328@ 值是国家名称,然后对于Cities,您使用Select LinQ 方法,该方法允许您构造另一个实体的列表。您使用Name = country.CityPopulation = country.Population 构造一个CityInfo 对象,如下所示。

    listGlobalInfo 是一个列表,包含来自 mongoDB 的所有文档,类型为 GlobalInfo

     var newList = from globalInfo in listGlobalInfo
                    group globalInfo by globalInfo.Country into country
                        select new CountryInfo{ Name = country.Key, Cities = country.Select(city=> new CityInfo { Name = city.City, Population = city.Population}).ToList()};
    

    如果您想查看更多group 查询示例,您可以转到https://docs.microsoft.com/en-us/dotnet/csharp/linq/group-query-results

    【讨论】:

    • 感谢您提供样品。但实际上我正在寻找使用来自 mongodb c# 驱动程序的流利聚合的解决方案,如下所示: var results = myMongodbCollection.Aggregate().Group( x => x.Country, g => new { CountryName = g.Key , ...
    • 哎呀,我的糟糕 OP :) 找到了一些示例 mikaelkoskinen.net/post/…
    • 感谢您的链接。不幸的是,它不是基于最新的 mongodb c# 驱动程序,也没有使用 lambda 表达式时类型安全的示例。
    猜你喜欢
    • 1970-01-01
    • 2016-12-25
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    相关资源
    最近更新 更多