I have a MongoDB collection named Venue
with elements of type:
{
venue: "Grand Hall",
sections: [{
name: "Lobby",
drinks: [{
name: "Vodka",
quantity: 3
}, {
name: "Red Wine",
quantity: 1
}]
}, {
name: "Ballroom",
drinks: [{
name: "Vodka",
quantity: 22
}, {
name: "Red Wine",
quantity: 50
}]
}]
}
I want to calculate the total amounts of each drink for the party. So I want my result to be something like that:
{
venue: "Grand Hall",
sections: 2,
drinks: [{
name: "Vodka",
quantity: 25
}, {
name: "Red Wine",
quantity: 51
}]
}
2
Answers
$unwind
– Deconstructsections
array into multiple documents.$unwind
– Deconstructsections.drinks
array into multiple documents.$group
– Group byvenue
andsections.drinks.name
. Perform sum forquantity
.$group
– Group byvenue
. Perform count for grouped result in previous stage. And add the document intodrinks
array.Demo @ Mongo Playground
There are lots of ways to do this. Here’s another one using
"$reduce"
and"$map"
, etc.Try it on mongoplayground.net.