Open In App

Mongoose Aggregate.prototype.exec() API

Improve
Improve
Like Article
Like
Save
Share
Report

The Aggregate API.prototype.exec() method of the Mongoose API is used to perform aggregation tasks. It allows us to execute the aggregate pipeline on the current Model. It takes a callback function as a parameter and returns a promise.

Syntax:

aggregate.exec( callback )

Parameters: This method accepts a single parameter as discussed below:

  • callback: It is used to handle the promise returned by the method.

Return Value: This method returns a promise which can be handled using callback function or using async-await.

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 have added pipeline operation to select name field from the collection. And we are calling exec() method to get the result set.

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([{ $project: { name: 1 } }])
    .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:

[
  { _id: 3, name: 'Ben Stokes' },   
  { _id: 2, name: 'David Warner' }, 
  { _id: 5, name: 'Aaron Finch' },  
  { _id: 7, name: 'K L Rahul' },    
  { _id: 6, name: 'Hardik Pandya' },
  { _id: 1, name: 'Virat Kohli' },  
  { _id: 4, name: 'Rohit Sharma' }  
]

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 handling the promise returned by exec() method using asynchronous function and await keyword.

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);
  
const execExample = async () => {
    const result = await Cricketer
        .aggregate([{
            $project: { nationality: 1, _id: 0, name: 1 }
        }])
        .exec();
    console.log(result);
}
execExample();


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

node app.js

Output:

[
  { name: 'Ben Stokes', nationality: 'England ' },   
  { name: 'David Warner', nationality: 'Australia' },
  { name: 'Aaron Finch', nationality: 'Australia ' },
  { name: 'K L Rahul', nationality: 'India ' },      
  { name: 'Hardik Pandya', nationality: 'India ' },  
  { name: 'Virat Kohli', nationality: 'India' },     
  { name: 'Rohit Sharma', nationality: 'India ' }    
]

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



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