Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

212
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

0

Solved my problem :

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

Thanks for helping!

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda