Best way to select N random documents from a collection?

My use-case: I want to show N randomly selected users on a page. There’s a $sample aggregation method in 3.2, but my Meteor instance is using 2.6.7, so I can’t use that.

Other solutions are mentioned here:

but most of them would only return 1 document, not N.

The only solution I found so far is to use a geo-spatial index on random numbers (also mentioned in the SO answers above). But this would always return the users in a specfic order, based on the random number chosen for the selection. I would need a true random sort order of all N users to be returned.

Is there any other solution out there to pick N documents out of all documents in a collection?

1 Like

If it is not too late to add a new field to your users collection, I can think of a naive, not-too-performant, but easy way.

What you’d do is add a field which will be an autoincrement integer

And then before querying for N random users, you’ll generate an array of N unique integers between 1 and users.count()

Finally you’ll do users.find({_id: {$in: array}})

There will probably be some quirks like repeating/missing numbers, but nothing too hard to work around with some clever use of a larger array and a {limit: N}.


Just be sure to apply this field only to users who finished the whole registration process, not the users who were written into the database. And it will grab the banned users too. But @serkandurusoy’s way to deal with that by using larger array will do.

1 Like