0

I'm very new to MongoDB and I have a problem. I want to select a random document but with a condition. In SQL I would have done something like this:

SELECT * FROM challenges
WHERE level = 1
ORDER BY RAND()
LIMIT 1

Now I need to do this in MongoDB, but I only get to the point where I select a random value

Challenge.aggregate({
        $sample: {size:1}
},

How can I add an WHERE statement, I've only seen it with challenge.find, but I'm already aggregating.

Any help would be highly appriciated.

1
  • 3
    aggregate have $match clause. That's your WHERE. Commented May 16, 2017 at 10:49

1 Answer 1

1
 Challenge.aggregate([
 {
   $match:{
     field1: condition1,
     field2: condition2
   }
 },
 {
    $sample: {size:1}
 }
])
Sign up to request clarification or add additional context in comments.

Comments

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.