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

138
Views
prevent MongoDB aggregate with $match from returning an empty Array

I have an aggregate function like this

 app.get('/feed', (req, res) => {
 TFBlog.aggregate([  
   { $sample: {size: 5} },
   { $match:  {"published": true} },
  
   ]).then((docs)=>{
   res.render('explore',{docs:docs});
 });
});

Now if aggregate finds a document that doesn't satisfy {published: true} it simply returns an empty array

So in many Use cases, I get 4 or 3 documents in return array instead of 5

I want this function to always return 5 random documents with $match criteria no matter what!!

How can I achieve this please explain?

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

0

Move $match condition to the top ?

db.collection.aggregate([  
   { $match:  {"published": true} },
   { $sample: {size: 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!