daniel aagentah
daniel aagentah

Reputation: 1702

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.

db.collection('articles')
.find()
.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.

Upvotes: 0

Views: 399

Answers (1)

Neodan
Neodan

Reputation: 5252

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:

db.collection('articles').aggregate([
   { $sample: { size: 4 } }
]);

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

Upvotes: 2

Related Questions