使用MongoDB聚合计数子数据

使用MongoDB聚合计数子数据,mongodb,aggregation-framework,Mongodb,Aggregation Framework,以下是我在mongodb中的数据: { "data": { "order_goods": [{ "category": 235 }, { "category": 666 }] } }, { "data": { order_goods: [{ "category": 235 }] } } 以下是我的预期输出: {"category":235, "total":2} {"cate

以下是我在mongodb中的数据:

{
    "data": {
    "order_goods": [{
        "category": 235
    }, {
        "category": 666
    }]
    }
}, {
    "data": {
    order_goods: [{
        "category": 235
    }]
    }
}
以下是我的预期输出:

{"category":235, "total":2}
{"category":666, "total":1}
我尝试了许多方法来处理聚合,例如
$group
,但结果总是这样:

{ "_id" : [ 235, 666 ], "total" : 1 }
{ "_id" : [ 235 ], "total" : 1 }
谢谢你的帮助。

试试这个

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

说明:当您尝试分组时,mongodb认为订单商品的完整数组是唯一的,因此您需要先$unwind,然后才能按单个类别进行分组。

请尝试以下查询:

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

看到了吗?你可以发布你尝试过的东西吗?哦,太棒了~~当我使用$REWIND时,它会起作用。