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"}


Leave a Comment