Is there a way in mongo for me to specify a format of how I want data returned?
I would like to be able to return items as an array if possible. Lets look at this very basic example:
{
color: red
},
{
color: white
},
{
color: blue
}
So for this example I would like to get the above documents as an array:
{
colors: [red, white, blue]
}
Is there any way to specify how to return items? I know I can specify which columns to get, but then I have to loop through them to build the array. I am hoping mongodb has this built in, as it can probably do it faster than node, php, java, etc.
Use aggregation framework. The aggregation pipeline would simply have a $group
operation where the $addToSet
operator adds the values to an array. For instance, with a collection which 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 the desired output:
/* 1 */
{
"result" : [
{
"colors" : [
"blue",
"white",
"red"
]
}
],
"ok" : 1
}