Reputation: 410
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.
Upvotes: 0
Views: 242
Reputation: 4678
Challenge.aggregate([
{
$match:{
field1: condition1,
field2: condition2
}
},
{
$sample: {size:1}
}
])
Upvotes: 1