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

110
Vistas
Find number of objects in nested array with different query params

I have this Event array but can't figure out how to query into the 'guests' nested array and do two things.

  1. count the number of guests

  2. count the number of attended guests (marked 'Y')

    { _id: new ObjectId('1'),
      name: event1,
      guests: [
        {
          phone: +12222222222,
          _id: new ObjectId,
          attended: 'Y'
        },
        {
          phone: +12344466666,
          _id: new ObjectId,
          attended: 'Y'
        },
        { phone: +11234567890, 
          _id: new ObjectId,
          attended: 
        },
        {
          phone: +14443332222,
          _id: new ObjectId,
          attended: 'Y'
        },
        { phone: +19090909090, 
          _id: new ObjectId
          attended:
        }
      ],
    },
    
    { _id: new ObjectId('2'),
      name: event2,
      guests: [
        {
          phone: +11111111111,
          _id: new ObjectId,
          attended:
        },
        {
          phone: +12222222222,
          _id: new ObjectId,
          attended: 'Y'
        },
        { 
          phone: +133333333333, 
          _id: new ObjectId,
          attended: 'Y'
        }
      ],
    },
    

My code below is on its 20th iteration without getting any closer.

const event = await Event.findById(req.params.id);
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

For MongoDB query, you can use $size for calculating the size of the array field and $filter to filter specific document(s) that matched the criteria in the projection.

db.collection.find({
  _id: "1"
},
{
  _id: 1,
  name: 1,
  guests: 1,
  totalGuests: {
    $size: "$guests"
  },
  attendedGuests: {
    $size: {
      "$filter": {
        input: "$guests",
        cond: {
          $eq: [
            "$$this.attended",
            "Y"
          ]
        }
      }
    }
  }
})

Sample Mongo Playground

about 4 years ago · Juan Pablo Isaza Denunciar

0

Yong Shun helped above but didn't get 100% of the way -- here is the full answer in case anyone encounters something like this in the future:

module.exports.showEvent = async (req, res) => {
    const event = await Event.findById(req.params.id).populate('artist');
    const { guest_id } = req.cookies;
    let totalGuests = 0;
    let attendedGuests = 0;
    const eventData = await Event.aggregate([
        {
            "$match": {
                "_id": objectId(req.params.id)
            }
        },
        {
            $project: {
                _id: 1,
                name: 1,
                guests: 1,
                totalGuests: { $cond: { if: { $isArray: "$guests" }, then: { $size: "$guests" }, else: "NA" } },
                attendedGuests: {
                    $size: {
                        $filter: {
                            input: "$guests",
                            as: "guest",
                            cond: {
                                $and: [{
                                    $eq: ["$$guest.attended", "Y"]
                                }]
                            }
                        }
                    }
                }
            }
        }
    ])
    if (eventData && Array.isArray(eventData) && eventData.length > 0) {
        totalGuests = eventData[0].totalGuests;
        attendedGuests = eventData[0].attendedGuests;
    }
    if (!event) {
        req.flash('error', 'Cannot find that Event');
        return res.redirect('/events');
    }
    res.render('events/show', { event, eventData });
    console.log(totalGuests, attendedGuests);
};    
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