How to flatten mongodb collection?


#1

I have a collection called programs with the following format:

{
"_id": “bdbdng3xygl”,
“name”: “Test”,
“exercise” : [
{
“groupNumber”: “1”,
“exerName”: “test1”
},
{
“groupNumber”: “2”,
“exerName”: “test2”
}
]
}

Is there a way to flatten this out so that I can get data in the format below?
[{“name”: “Test”, “groupNumber”: “1”,“exerName”:"test1},{“name”: “Test”, “groupNumber”: “2”,“exerName”:"test2} ]

Any help would be greatly appreciated. I am new to meteor and mongo and am totally stuck on how to write a helper to get data in this format so that I can iterate over it and display in a table. Thanks!


#2

Maybe:

{{#each program}}
  {{#each exercise}}
    {{../name}}
    {{groupNumber}}
    {{exerName}}
  {{/each}}
{{/each}}

#3

Use map from underscore / lodash:

var col_name = collection.name;
var new_array = _.map(collection.exercise, function(val) {
    return { name: col_name, groupNumber: val.groupNumber, exerName: val.exerName };
}

#4

Thanks! This worked.


#5

Thanks for the tip. The first option worked for me and so didn’t have to try your suggestion but I am going to look at underscore in detail. I think it will be useful.


#6

You can also use the aggregation framework of MongoDB - you can read MongoDB $unwind docs. To utilize the framework you have to use a meteor package such as meteorhacks/aggregate. This has to be done server side only as MiniMongo unfortunately doesn’t support the framework.