Mongo $group with $project

Prashant Thorat picture Prashant Thorat · Feb 3, 2016 · Viewed 44.5k times · Source

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?

Answer

chridam picture chridam · Feb 3, 2016

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)