This is a bit trickier than one might first think. Or maybe I am just overthinking the problem.
Here is how I retrieve (two) random documents from MongoDB:
Character
.find({ random: { $near: [Math.random(), 0] } })
.where('voted', false)
.limit(2)
.exec(function(err, characters) {
res.send({ characters: characters });
}
});
What I would like to add is - finding by gender. Each document already has a gender field with value set to either female or male. What I need in other words: Give me two random documents that have a matching gender field.
Example: 2 random females, 2 random males, 2 random males, 2 random females, etc...
For more information on how to retrieve a random document from MongoDB: http://cookbook.mongodb.org/patterns/random-attribute/