[SOLVED] Random record from mongo db

A user should get a random question which he hasn’t already answered. answers is an array with already answered questions.

var rnd = Math.random();
var questionSet = Questions.findOne({ $query: {number: {$gt: rnd}, _id: {$nin: answers}}, $orderby: { number: 1 }});
if (questionSet === null) {
    questionSet = Questions.findOne({ $query: {number: {$lte: rnd}, _id: {$nin: answers}}, $orderby: { number: 1 }});
}

As soon as the size of answeres is Questions.find().count() -1, I didn’t get a result. So I couldn’t fetch the last question.

BUT when I’m executing the same in mongo chef console I will also get the last question.


var rnd = Math.random();

var questionSet = db.questions.findOne({$query: {number: {$gt:rnd}, _id: {$nin: answers}} , $orderby: {number:1} } );
if (questionSet === null) {
    questionSet = db.questions.findOne({$query: {number: {$lte: rnd}, _id: {$nin: answers}}, $orderby: {number:1} });
}

problem is that questionSet is not null but undefined.

if (!questionSet) {

works fine.