1

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>> 
3
  • The aggregation framework will be your buddy here; have a look at the $group pipeline operator, where you can group the documents by the id key and create the records array using the $push operator. Commented Jan 4, 2016 at 17:26
  • Isn't this ironic that you use nosql and try to get normalized sql-like output? Maybe you should just rethink your database choice? Commented Oct 12, 2016 at 15:09
  • @Stan What about my question is "sql-like"? I don't see the harm in the question... there a lots of reasons to use mongo (or nosql in general) aside from what is shown in this question. Why not try and normalise the data when reading if i would be doing later down the line in code anyway? Commented Oct 12, 2016 at 15:22

1 Answer 1

1

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 }); 
Sign up to request clarification or add additional context in comments.

1 Comment

It is indeed old! So I can't test directly against what i was doing but i think this would work for what i was after...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.