I have the collection below, I need to make a query that group by confrontationId and display the results as expected, is there a way to do this with MongoDB, I need to group only the matches..
{
"rounds": {
"matches": [{
"id": "8cac353e-fb04-4a9a-b340-ed64e1094ff1",
"confrontationId": "2f2c58c9-f1be-4914-8aee-03d00725a0be",
"arena": "Tacoma Dome",
"status": "FINISHED"
},
{
"id": "d8ff6322-824c-455c-b59d-d837d0188d93",
"confrontationId": "41d85805-5571-42c6-a38e-e03fd8fcdc96",
"arena": "Baku Crystal Hall",
"status": "FINISHED"
},
{
"id": "e23dc4ce-24de-4f7f-b5b0-9b124ec0e71a",
"confrontationId": "2f2c58c9-f1be-4914-8aee-03d00725a0be",
"arena": "Greensboro Coliseum",
"status": "FINISHED"
}
]
}
}
Expected:
[
[{
"id": "8cac353e-fb04-4a9a-b340-ed64e1094ff1",
"confrontationId": "2f2c58c9-f1be-4914-8aee-03d00725a0be",
"arena": "Tacoma Dome",
"status": "FINISHED"
},
{
"id": "e23dc4ce-24de-4f7f-b5b0-9b124ec0e71a",
"confrontationId": "2f2c58c9-f1be-4914-8aee-03d00725a0be",
"arena": "Greensboro Coliseum",
"status": "FINISHED"
}
],
[{
"id": "d8ff6322-824c-455c-b59d-d837d0188d93",
"confrontationId": "41d85805-5571-42c6-a38e-e03fd8fcdc96",
"arena": "Baku Crystal Hall",
"status": "FINISHED"
}]
]
CodePudding user response:
$unwind
unwind$rounds.matches
$group
group by confrontationId and push root to item
db.collection.aggregate([
{
"$unwind": "$rounds.matches"
},
{
"$group": {
"_id": "$rounds.matches.confrontationId",
"items": {
$push: "$$ROOT"
}
}
}
])