mongodb - Specify Return Format -
is there way in mongo me specify format of how want data returned?
i able return items array if possible. lets @ basic example:
{ color: red }, { color: white }, { color: blue }
so example above documents array:
{ colors: [red, white, blue] }
is there way specify how return items? know can specify columns get, have loop through them build array. hoping mongodb has built in, can faster node, php, java, etc.
use aggregation framework. aggregation pipeline have $group
operation $addtoset
operator adds values array. instance, collection has sample documents:
/* 1 */ { "_id" : objectid("553c0101dddf8dcf96bdcdea"), "color" : "red" } /* 2 */ { "_id" : objectid("553c0101dddf8dcf96bdcdeb"), "color" : "white" } /* 3 */ { "_id" : objectid("553c0101dddf8dcf96bdcdec"), "color" : "blue" }
the following aggregation
db.collection.aggregate([ { "$group": { "_id": 0, "colors": { "$addtoset": "$color" } } }, { "$project": { "_id": 0, "colors": 1 } } ])
will produce desired output:
/* 1 */ { "result" : [ { "colors" : [ "blue", "white", "red" ] } ], "ok" : 1 }
Comments
Post a Comment