1

我有一个名为“UserRecords”的集合。结构如下

  {
    "_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",   
}

和更多...

现在我想让 Max 点击每个类别。使用最新的 Mongo C# 驱动程序,例如

    select Max(clicked) from table group by Category in SQL.
4

1 回答 1

2

像这样的查询可以使用 MongoDB Aggregation Framework有效地处理。但是,查询是以 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"]}");
}
于 2016-02-23T15:39:17.180 回答