Home > Mobile >  Mongodb : Project array value in lookup
Mongodb : Project array value in lookup

Time:05-05

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 !

CodePudding user response:

Well if you receive several of those objects in an array, to sum them is fairly straightforward:

const sum = objectArr.reduce((acc, { resa }) => acc   (resa.reduce((acc, { adultCount }) => acc   (adultCount || 0), ), 0);

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 an adultCount property), then it's a lot simpler:

const sum = objectArr.reduce((acc, { resa: [ adultCount ]}) => acc   adultCount, 0);

CodePudding user response:

Solved my problem :

adults: { $sum: {
            '$sum':'$resa.adultCount'
        }},

Thanks for helping!

  • Related