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

423
Views
How to query a sub document that is less than a particular size in mongoose?

I have a game object that has a boolean isOpen and a sub document playersthat is an array of players. I'd like to find a game that is open for players to join that contains less than 5 players. How do I do this? Preferably without using $where

//made up sample for reference  
const sampleDocument = {
    isOpen: true,
    isOver: false,
    players : [{
        socketID: 'sldfjskdfjsjdfsdfj',
        isBot: false,
        name: 'NickName',
    }],
    startTime: 32343234

The relevant line of code

let game = await Game.findOne({isOpen: true, /*players : { $size: {$lt: 5} }*/})
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You need $expr.

db.collection.find({
  $expr: {
    $and: [
      {
        $eq: [
          "$isOpen",
          true
        ],
        
      },
      {
        $lt: [
          {
            "$size": "$players"
          },
          5
        ]
      }
    ]
  }
})
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!