danjones_mcr danjones_mcr - 3 years ago 272
Node.js Question

MongoDB - return X number of random records

In my node.js server, I am trying to return 4 random records from my collection.

Here is my current code, the issue is that currently it returns between 0-4 random records from my collection, whereas I want to return 4 (no more no less) random records every time.

.limit( 4 )
.skip(Math.round(Math.random() * 4))
.sort("date", -1).toArray()

Any help or advice is appreciate - thank you in advance!

I had a look at some similar questions but they all only seem to
generate random records between 0-X records, not a set amount.

Answer Source

You can use $sample aggregation pipeline for that.

Randomly selects the specified number of documents from its input.

The $sample stage has the following syntax:

{ $sample: { size: <positive integer> } }

E.g. this code returns 4 random documents:

   { $sample: { size: 4 } }

If you need to select x random documents by some criterias, then just add $match

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download