I am trying to get keyword count along with parentId
, categioryId
and llcId
. My db is
{ "_id" : ObjectId("5673f5b1e4b0822f6f0a5b89"), "keyword" : "electronic content management system", "llcId" : "CL1K9B", "categoryId" : "CL1K8V", "parentId" : "CL1K8V", }
I tried $project
with $group
db.keyword.aggregate([ { $group: { _id: "$llcId", total: {$sum: 1}, } }, { $project: { categoryId: 1, total: 1 } } ])
And it gives me a result like
{ "_id" : "CL1KJQ", "total" : 17 } { "_id" : "CL1KKW", "total" : 30 }
But I need actual data in result also e.g. llcId
, categoryId
, keyword
, total
. I tried to display cetgoryId
and keyword by using $project
but it displays only _id
and total. What I am missing?
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 } }])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With