Search code examples
c#mongodbmongodb-.net-driver

Mongodb Group into Dictionary style structure


Let's say I have the following records:

{ id: 1, value : 1, Date: 2016-01-01 },
{ id: 1, value : 2, Date: 2016-01-01 },
{ id: 2, value : 3, Date: 2016-01-01 },
{ id: 3, value : 4, Date: 2016-01-01 }

In mongodb C# driver how would I call a collection with this data format to produce something like:

 { 
    {
      id: 1, 
      records : [
        {value : 1, Date: 2016-01-01}, 
        {value : 2, Date: 2016-01-01}
    ]}, 
   { 
      id : 2, 
      records : [{value : 3, Date: 2016-01-01}] 
   },
   { 
      id : 3, 
      records : [{value : 4, Date: 2016-01-01}] 
   }
}

So i want to group on the "id" field and then return all results grouped by their id as a list. So the structure would be something like C#'s

 Dictionary<int, List<MyObj>>

Solution

  • Just realised this is an old question... but if anyone comes across it:

    I've not got mongo up at the moment to test, but you should be able to use aggregations via linq, something like:

    var query = collection.AsQueryable()
                          .GroupBy(r => r.Id)
                          .Select(g => new { id = g.Key, records = g.Value });