using MongoDB aggregate count subdata

119 Views Asked by At

here is my data in mongodb:

{
    "data": {
    "order_goods": [{
        "category": 235
    }, {
        "category": 666
    }]
    }
}, {
    "data": {
    order_goods: [{
        "category": 235
    }]
    }
}

here is my expected output:

{"category":235, "total":2}
{"category":666, "total":1}

I have try many ways about aggregate such as $group, but result always like:

{ "_id" : [ 235, 666 ], "total" : 1 }
{ "_id" : [ 235 ], "total" : 1 }

Thanks for your help.

2

There are 2 best solutions below

0
On BEST ANSWER

please try the below query :

db.collection.aggregate(
 [
  { "$unwind": "$data.order_goods" },
  { "$group" : { "_id" : "$data.order_goods.category", 
    "total": {"$sum":1} } },
  { "$project" : { "category" : "$_id" , total : 1 }
 ]
 );
0
On

try this

db.test.aggregate([{ "$unwind":"$data.order_goods"}, {"$group":{_id:"$data.order_goods.category","count":{$sum:1}}}])

Explanation : When you try to group without $unwind, mongodb considers the complete array of order_goods to be unique, therefore you need to first $unwind before you can group by individual category.