Open In App

Mongoose Aggregate.prototype.sample() API

Last Updated : 16 May, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

The Mongoose Aggregate.prototype.sample() API is a powerful aggregation method used to randomly select a specified number of documents from a MongoDB collection. It helps developers retrieve a random sample of data without having to manually query for specific entries. This feature is particularly useful when you need random data from a collection for tasks such as testing, analytics, or random selection.

How Mongoose's Aggregate.prototype.sample() Works

The Aggregate API.prototype.sample() method of the Mongoose API is used to perform aggregation tasks. It allows us to get the sample result set from the collection. We can specify the number of documents we want from the collection. This method is used to randomly select specified number of documents from the collection and return a single result set.

Syntax:

aggregate.sample( <number> )

Parameters:

  • number: This is the number of documents that you wish to randomly extract from the collection. It is a required parameter and should be a positive integer.

Return Value

It returns result set in the form of array, containing number of documents specified as a parameter to the method. The length of the array is determined by the number you specify.

Setting up Node.js Application with Mongoose

Here’s how you can set up your Node.js project to use Mongoose's sample() method.

Step 1: Create a Node.js Application

Open your terminal and create a new Node.js project using the following command:

npm init

Step 2: Install the Mongoose Module

After creating the NodeJS application, Install the required module using the following command:

npm install mongoose

Project Structure: The project structure will look like this: 

 

Database Structure: The database structure will look like this, the following documents are present in the collection.

Example 1: Using sample() to Select Random Documents

In this example, we have established a database connection using mongoose and defined model over cricketerSchema, having three columns or fields "_id", "name", and "nationality". At the end, we are calling sample() method to get 3 documents randomly from collection.

Filename: app.js

JavaScript
// Require mongoose module
const mongoose = require("mongoose");

// Set Up the Database connection
mongoose.connect("mongodb://localhost:27017/geeksforgeeks", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});

const cricketerSchema = new mongoose.Schema({
    _id: Number,
    name: String,
    nationality: String
});

const Cricketer = mongoose.model('Cricketers', cricketerSchema);

Cricketer.aggregate().sample(3)
    .then((successCb, errorCb) => {
        if (successCb) {
            console.log(successCb);
        } else {
            console.log(errorCb);
        }
    })

Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

[
  { _id: 6, name: 'Hardik Pandya', nationality: 'India ', __v: 0 }, 
  { _id: 4, name: 'Rohit Sharma', nationality: 'India ', __v: 0 },  
  { _id: 5, name: 'Aaron Finch', nationality: 'Australia ', __v: 0 }
]

Example 2: Using sample() to Select Random Documents with Additional Operations

In this example, we have established a database connection using mongoose and defined model over cricketerSchema, having three columns or fields "_id", "name", and "nationality". At the end, we are getting 4 documents randomly from the collection. In this example, we are using operator operation to extract the result. 

Filename: app.js

JavaScript
// Require mongoose module
const mongoose = require("mongoose");

// Set Up the Database connection
mongoose.connect("mongodb://localhost:27017/geeksforgeeks", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});

const cricketerSchema = new mongoose.Schema({
    _id: Number,
    name: String,
    nationality: String
});

const Cricketer = mongoose.model('Cricketers', cricketerSchema);

Cricketer.aggregate([{ $sample: { "size": 4 } }])
    .exec((error, result) => {
        if (error) {
            console.log(error);
        } else {
            console.log(result);
        }
    })

Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

Note: The output may vary as the documents are randomly selected each time.

[
  { _id: 7, name: 'K L Rahul', nationality: 'India ', __v: 0 },     
  { _id: 6, name: 'Hardik Pandya', nationality: 'India ', __v: 0 }, 
  { _id: 4, name: 'Rohit Sharma', nationality: 'India ', __v: 0 },  
  { _id: 5, name: 'Aaron Finch', nationality: 'Australia ', __v: 0 }
]

Conclusion

The sample() method in Mongoose's aggregation framework is an efficient way to randomly select a specified number of documents from a collection. This is particularly useful when we need a random selection of data for tasks like sampling, testing, or analytics. By using this method in your applications, you can easily extract a subset of random documents without needing to write complex queries or perform additional logic.


Similar Reads