Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

205
Views
Mongodb : Project array value in lookup

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 !

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);
about 4 years ago · Juan Pablo Isaza Report

0

Solved my problem :

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

Thanks for helping!

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!