Andrew Polidori
Andrew Polidori

Reputation: 63

Is it possible to select a random document once and then never again?

I'm looking for a way to select a document from a MongoDB randomly, and then exclude it from any other random selections.

I'm familiar with the .skip(someRandomNumber).next() method for random choice. But how to exclude it from further choices.

The scenario is a collection of situations which have to be selected/loaded randomly, but can't be loaded more than once.

Any ideas?

Upvotes: 1

Views: 68

Answers (1)

alekseevi15
alekseevi15

Reputation: 1782

Have you seen The Random Attribute approach? The idea is to assign "random attribute" to each document. Then in your application you could generate random number, remember it(to not use it in future), and select random document from a collection.

Another approach would be to select random document from a collection, then mark this document as already selected(not to select it in future). So, when querying you explicitly filter out documents that already were selected before.

Upvotes: 1

Related Questions