Reputation: 61
I need to group the objects inside of votes by mallId inside of a mongodb aggreate pipeline. Been searching for an answer for ages, but I am not too familiar with mongodb so I am kind of lost. Can anyone help me out?
[
{
"_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
}
]
}
]
Upvotes: 6
Views: 7308
Reputation: 10918
Given the following document structure
{
"_id" : ObjectId("5a020ea06216d24dd6050a07"),
"arr" : [
{
"_id" : "Specialty Retailer",
"votes" : [
{
"mallId" : "59ddea3718a03a4e81f289f5",
"count" : 13
},
{
"mallId" : "59ddea3718a03a4e81f289f5",
"count" : 270
}
]
}
]
}
this query should get you going:
db.collection.aggregate({
$unwind: "$arr"
}, {
$unwind: "$arr.votes"
}, {
$group: {
"_id": {
"_id": "$_id",
"arrId": "$arr._id",
"mallId": "$arr.votes.mallId"
},
"totalCount": {
$sum: "$arr.votes.count"
}
}
})
Upvotes: 2