Converting mongo array to object with key-value pair
Not so sure what you want to do with the end result as the keys and the values are just the same. Nonetheless, you can use the aggregation frameworkwhere you can denormalise the embedded values array by using the $unwind
operator which flattens it i.e. it produces a copy of each document per array entry.
After flattening the values array, you can apply the $group
accumulation operators on the values to aggregate them. A final pipeline of the $project
operator would shape the fields from the previous grouping into the desired format.
Follow this example to get the concept:
templateAttributes.aggregate([ { "$match": { "platform": "V1" } }, { "$unwind": "$available.Community.attributes.type.values" }, { "$group": { "_id": "$available.Community.attributes.type.values", "value": { "$first": "$available.Community.attributes.type.values" } } }, { "$project": { "_id": 0, "label": "$_id", "value": 1 } }])
Since you are using Meteor, meteor add meteorhacks:aggregate
will add proper aggregation support for Meteor so that you can run the above aggregation pipeline on your collection.
Please use aggregation here.
db.templateAttributes.aggregate([ {"$match":{platform:"A1"}}, {"$unwind": "$available.Community.attributes.type.values"}, {$group: {"_id": null, "val":{"$push":{label:"$available.Community.attributes.type.values", value:"$available.Community.attributes.type.values"}}}} ]).toArray()[0].val
Output:
[ { "label" : "well-known", "value" : "well-known" }, { "label" : "simple", "value" : "simple" }, { "label" : "complex", "value" : "complex" }]
Use query
templateAttributes.aggregate([{$match: { "platform" : "A1" }}, { $unwind: {path : "$available.Community.attributes.type.values"}},{ $group:{ _id:"$_id", result:{ $push: { label: "$available.Community.attributes.type.values", value: "$available.Community.attributes.type.values" } } }}])
It'll give you exact your expected answer.