GroupBy Mongodb 与驱动程序 C#

GroupBy Mongodb with Driver C#

我正在制作一个统计模块,我需要执行一个带有计数的 GroupBy 操作,以按国家/地区统计访问者总数。我正在使用 MongoRepository (Link to Library)

我在 C# 中使用此代码运行良好,但我不喜欢该解决方案:

var repositoryIpFrom = new MongoRepository<IpFrom>();
var countries = repositoryIpFrom.Where(s => s.id == id).Select(s => s.Country).Distinct();

            foreach (var country in countries)
            {
                statisticsCountryDto.Add(new StatisticsCountryDto()
                {
                    Country = country,
                    Count = repositoryIpFrom.Count(s => s.id == id && s.Country == country)
                });
            }

            return statisticsCountryDto;

还有这个与 Linq 一起使用(但它不起作用...错误提示不支持 GroupBy)

 var tst = repositoryIpFrom.Where(s=>s.id == id).GroupBy(s => s.Country).Select(n => new
            {
                Country = n.Key,
                Count = n.Count()
            });

我可以选择创建 GroupBy 而不进行大量查询吗?

谢谢!!

由于不是通过query进行过滤,所以可以通过插入一个AsEnumerable操作来解析query,然后在MongoDb驱动不再参与后对本地数据进行分组操作.

var tst = repositoryIpFrom
            .Where(s=>s.id == id)
            .AsEnumerable()
            .GroupBy(s => s.Country)
            .Select(n => new
            {
               Country = n.Key,
               Count = n.Count()
            });