2

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?

1
  • In your case match condition should pass. it simply returns an empty array is wrong. Can you show us the sample documents with necessary fields and expected output Commented Aug 24, 2021 at 8:45

1 Answer 1

1

Move $match condition to the top ?

db.collection.aggregate([  
   { $match:  {"published": true} },
   { $sample: {size: 5} }
])
Sign up to request clarification or add additional context in comments.

1 Comment

good God it worked!! thanks man I ignored the staging order !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.