Reputation: 285
I'm trying to do a simple GROUP BY/COUNT in mongodb with this aggregation query:
{
$match:{
'os':7
}
},
{
$group : {
_id:"$status",
count:{$sum:1}
}
},
{
$project:{
count:1,
status:1
}
}
It's return an array like this
[{ "_id" : "ENC", "count" : 18 }
{ "_id" : "INT", "count" : 363 }
{ "_id" : "ANN", "count" : 132 }]
Is there a way to project the result in an object, using the grouping field as a key ? For example:
{
ENC:18,
INT:363,
ANN:132
}
Thanks
Upvotes: 2
Views: 514
Reputation: 103475
I don't think MongoDB's aggregation framework has $project
operations that can convert field values into keys. You could try convert the aggregation result using the forEach()
cursor method to iterate over the projected fields and use JavaScript's bracket-notation on the result object to then create desired final object:
var result = [
{ "_id" : "ENC", "count" : 18 },
{ "_id" : "INT", "count" : 363 },
{ "_id" : "ANN", "count" : 132 }
];
var obj = {};
result.forEach(function (doc){
obj[doc._id] = doc.count;
});
printjson(obj); // {ENC: 18, INT: 363, ANN: 132}
Upvotes: 1