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

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

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

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 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