In a jointed aggregation (with lookup), I’m trying to sum values of a key in the following "resa" field, groupped in a projection (see code snippet #2).
Context:
Here I’m trying to sum the amount of "adultCount" values for every results. Here is the data I’m retrieving before groupping.
{
"_id" : ObjectId("626961e60e561759af0b0c5d"),
"grossValue" : 26.37,
"netValue" : 23.97,
"state" : "Closed",
"resa" : [
{
"adultCount" : 1
}
]
}
The full Query here :
db.items.aggregate([
{
$match:{
// matching condition
}
},
{
$lookup:{
from: 'reservations',
localField: 'orderId',
foreignField: 'reservationId',
as: 'resa',
}
},
{
$project:{
_id: 1,
state: 1,
grossValue: 1,
netValue: 1,
'resa.adultCount': 1
}
},
{
$group:{
_id: '$state',
count: { $sum: 1 },
grossValue: { $sum: '$grossValue'},
netValue: { $sum: '$netValue' },
adults:{$sum: '$resa[0].adultCount'} // <--- HOW TO SUM THE VALUES HERE?
}
}
]);
Thank you !
2
Answers
Solved my problem :
Thanks for helping!
Well if you receive several of those objects in an array, to sum them is fairly straightforward:
It’s a bit clunky just because I’m avoiding any non-numeric additions resulting from a lack of data – if you’re certain of the data being always that structure (i.e. one element in the
resa
array, always with anadultCount
property), then it’s a lot simpler: