C#中使用MongoDB聚合分组将扁平文档转为国家城市层级结构
MongoDB C#驱动扁平文档转层级结构实现方案
首先你需要先初始化对应集合的IMongoCollection<GlobalInfo>实例,以下是两种实现方案:
方案1:服务端聚合实现(推荐大数据量场景)
该方案的分组、转换逻辑都在MongoDB服务端执行,仅返回最终需要的层级数据,减少网络传输和客户端内存占用:
// 替换为你实际的数据库实例和集合名称 var collection = mongoDatabase.GetCollection<GlobalInfo>("GlobalInfos"); // 直接聚合返回List<CountryInfo> List<CountryInfo> countryInfoList = collection.Aggregate() // 按需添加过滤条件,示例为仅筛选人口大于50万的城市 // .Match(info => info.Population > 500000) .Group( keySelector: info => info.Country, resultSelector: group => new { CountryName = group.Key, CityList = group.Select(item => new CityInfo { Name = item.City, Population = item.Population }).ToList() }) .Project(groupResult => new CountryInfo { Name = groupResult.CountryName, Cities = groupResult.CityList }) .ToList(); // 转成以国家名为键的字典 Dictionary<string, List<CityInfo>> countryCityDict = countryInfoList .ToDictionary(c => c.Name, c => c.Cities);
方案2:客户端内存转换(适合小数据量场景)
该方案先拉取所有符合条件的扁平数据,在客户端内存中完成分组转换,写法更简单灵活:
// 拉取所有需要的扁平数据,可按需添加Where过滤 List<GlobalInfo> allData = collection.AsQueryable() // .Where(info => info.Population > 500000) .ToList(); // 内存分组转CountryInfo列表 List<CountryInfo> countryInfoList = allData .GroupBy(info => info.Country) .Select(g => new CountryInfo { Name = g.Key, Cities = g.Select(item => new CityInfo { Name = item.City, Population = item.Population }).ToList() }) .ToList(); // 转字典 Dictionary<string, List<CityInfo>> countryCityDict = countryInfoList .ToDictionary(c => c.Name, c => c.Cities);
注意事项
- 数据量较大时优先使用服务端聚合方案,避免全量拉取数据导致客户端内存溢出
- 聚合操作支持链式调用
Skip、Limit方法实现分页查询 - 如果需要对城市列表排序,可以在分组时对
Select结果添加OrderBy逻辑
内容的提问来源于stack exchange,提问作者RickyTad
相关产品推荐
相关产品推荐

