[英]Using c# Mongodb driver 2.2, how to find max record when grouped by on a particular field
I have a collection as "UserRecords". 我有一个“ UserRecords”集合。 structure for this is as follows 其结构如下
{
"_id" : "ee654ce6-e50d-4243-8738-35c087a85e67",
"_t" : "Animals",
"ClickedOn" : NumberLong(1452600122),
"Category" : "Nature",
"UserId" : "a1",
}
{
"_id" : "ee654ce6-e50d-4243-8738-35c087a85e67",
"_t" : "Abstract",
"ClickedOn" : NumberLong(1247634566),
"Category" : "Modern",
"UserId" : "a1",
}
{
"_id" : "ee654ce6-e50d-4243-8738-35c087a85e67",
"_t" : "Abstract",
"ClickedOn" : NumberLong(1247634440),
"Category" : "Modern",
"UserId" : "a1",
}
and more... 和更多...
now I want to get Max clicked on for each category. 现在我想为每个类别点击“ Max”。 Using latest Mongo C# driver something like 使用最新的Mongo C#驱动程序类似
select Max(clicked) from table group by Category in SQL.
Queries like this can be efficiently processed with the MongoDB Aggregation Framework . 可以使用MongoDB 聚合框架有效地处理此类查询。 However, the queries are written as JSON, making them a bit hard to read. 但是,查询是用JSON编写的,因此使其难以阅读。
var dataCollection = Database.GetCollection("UserRecords");
var AggArgs = new AggregateArgs {
Pipeline =
new[] {BsonDocument.Parse(@"{$group : {_id : '$Category', ClickedOn : {$max : '$ClickedOn'}}}")}
};
foreach (var result in dataCollection.Aggregate(AggArgs))
{
Console.WriteLine($"Category: {result["_id"]} Clicked: {result["ClickedOn"]}");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.