[英]GroupBy Mongodb with Driver C#
I'm making a stadistics module and I need to do a GroupBy Operation with a Count to take the total visitors by country. 我正在创建一个stadistics模块,我需要使用Count进行GroupBy操作,以按国家/地区访问总访问者。 I'm using MongoRepository ( Link to Library ) 我正在使用MongoRepository( 链接到库 )
I have this code in C# working fine, but I don't like the solution: 我在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;
And this one with Linq (but it's not working... the error says GroupBy is not supported) 而这一个与Linq(但它没有工作......错误说GroupBy不受支持)
var tst = repositoryIpFrom.Where(s=>s.id == id).GroupBy(s => s.Country).Select(n => new
{
Country = n.Key,
Count = n.Count()
});
Can I have any options to make the GroupBy and not make a lot of queries? 我可以有任何选项来制作GroupBy而不会进行大量查询吗?
Thanks!! 谢谢!!
Since you are not filtering through the query, you can resolve the query by inserting a AsEnumerable
operation and then perform the grouping operations on the local data after the MongoDb driver is no longer involved. 由于您没有过滤查询,因此可以通过插入AsEnumerable
操作来解析查询,然后在不再涉及MongoDb驱动程序之后对本地数据执行分组操作。
var tst = repositoryIpFrom
.Where(s=>s.id == id)
.AsEnumerable()
.GroupBy(s => s.Country)
.Select(n => new
{
Country = n.Key,
Count = n.Count()
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.