Open In App

Mongoose Aggregate prototype.sample() API

Improve
Improve
Like Article
Like
Save
Share
Report

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: This method accepts a single parameter as discussed below:

  • number: It is the number of documents that are randomly extract from the collection.

Return Value: It returns result set in the form of array, containing number of documents specified as a parameter to the method.

Setting up Node.js application:

Step 1: Create a Node.js application using the following command:

npm init

Step 2: 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: 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
    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:

Note: Please do not compare your output with mine. Output may vary as this method pick documents randomly.

[
  { _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: 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
    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 that the output may vary as this method pick documents randomly.

[
  { _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 }
]

Reference: https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate-sample



Last Updated : 05 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads