Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

206
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

Solved my problem :

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

Thanks for helping!

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda