Search code examples
c#mongodbmongo-c-drivermongodb-.net-drivermongo-cxx-driver

Using c# Mongodb driver 2.2, how to find max record when grouped by on a particular field


I have a collection as "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. Using latest Mongo C# driver something like

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

Solution

  • Queries like this can be efficiently processed with the MongoDB Aggregation Framework. However, the queries are written as JSON, making them a bit hard to read.

    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"]}");
    }