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

169
Views
mongoose get only those documents if all subdocuments pass the criteria

Let's say I have a Lesson schema and it contains an array of question subdocuments. How would I get those lessons where it is marked as completed but all the questions in the array have isDeleted: true

I thought of something like

Lesson.find({ isComplete: true, 'questions.isDeleted': true })

but that gets the lessons if at least one of the questions is deleted. How would I assert the condition for all of the questions?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can't use the dot notation as it flattens the array, What you can do is use $expr, this allows the use of aggregation operators, like $reduce.

Now we can iterate over the array and see if all the documents satisfy the conditions, like so:

db.collection.find({
  isComplete: true,
  $expr: {
    $eq: [
      {
        $reduce: {
          input: "$questions",
          initialValue: 0,
          in: {
            $sum: [
              "$$value",
              {
                $cond: [
                  {
                    $ne: [
                      "$$this.isDeleted",
                      true
                    ]
                  },
                  1,
                  0
                ]
              }
            ]
          }
        }
      },
      0
    ]
  }
})

Mongo Playground

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!