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

103
Views
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 answers
Answer question

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 Report

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