Mongo $group with $project
To get the keyword
count you'd need to group the documents by the keyword
field, then use the accumulator operator $sum
to get the documents count. As for the other field values, since you are grouping all the documents by the keyword value, the best you can do to get the other fields is use the $first
operator which returns a value from the first document for each group. Otherwise you may have to use the $push
operator to return an array of the field values for each group:
var pipeline = [
{
"$group": {
"_id": "$keyword",
"total": { "$sum": 1 },
"llcId": { "$first": "$llcId"},
"categoryId": { "$first": "$categoryId"},
"parentId": { "$first": "$parentId"}
}
}
];
db.keyword.aggregate(pipeline)
You are grouping by llcId
so it will give more than one categoryId
per llcId
.
If you want categoryId
as in your result, you have to write that in your group query. For example:
db.keyword.aggregate([
{
$group: {
_id: "$llcId",
total: {$sum: 1},
categoryId:{$max:"$categoryId"}
}
},
{
$project: {
categoryId: 1, total: 1
}
}])