MongoDB:聚合对象数组内的数组中的对象

时间:2017-11-07 16:20:37

标签: mongodb aggregate

我需要在mongodb aggreate管道中通过mallId对投票内的对象进行分组。一直在寻找答案,但我不太熟悉mongodb所以我有点迷茫。任何人都可以帮助我吗?

     [
      {
        "_id": "Specialty Retailer",
        "votes": [
          {
            "mallId": "59ddea3718a03a4e81f289f5",
            "count": 13
          },
          {
            "mallId": "59ddea3718a03a4e81f289f5",
            "count": 270
          },
          {
            "mallId": "59ddea3718a03a4e81f289f5",
            "count": 13
          },
          {
            "mallId": "59ddea3718a03a4e81f289f5",
            "count": 2
          },
          {
            "mallId": "59ddea3718a03a4e81f289f5",
            "count": 15
          },
          {
            "mallId": "59ddea3718a03a4e81f289f5",
            "count": 2
          }
     ]
   }
]

1 个答案:

答案 0 :(得分:0)

给出以下文档结构

{
    "_id" : ObjectId("5a020ea06216d24dd6050a07"),
    "arr" : [ 
        {
            "_id" : "Specialty Retailer",
            "votes" : [ 
                {
                    "mallId" : "59ddea3718a03a4e81f289f5",
                    "count" : 13
                }, 
                {
                    "mallId" : "59ddea3718a03a4e81f289f5",
                    "count" : 270
                }
            ]
        }
    ]
}

此查询可以帮助您:

db.collection.aggregate({
    $unwind: "$arr"
}, {
    $unwind: "$arr.votes"
}, {
    $group: {
        "_id": {
            "_id": "$_id",
            "arrId": "$arr._id",
            "mallId": "$arr.votes.mallId"
        },
        "totalCount": {
            $sum: "$arr.votes.count"
        }
    }
})