Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo $group with $project

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?

like image 921
Prashant Thorat Avatar asked Feb 03 '16 12:02

Prashant Thorat


2 Answers

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) 
like image 161
chridam Avatar answered Sep 24 '22 00:09

chridam


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     } }]) 
like image 39
Sirisha Avatar answered Sep 23 '22 00:09

Sirisha