How to flatten mongodb collection?

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!

Maybe:

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

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 };
}

Thanks! This worked.

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.

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.