Mongoose Aggregate.prototype.exec() API
Last Updated :
16 May, 2025
Mongoose, a popular MongoDB ODM (Object Data Modeling) library for Node.js, provides a powerful API to perform advanced aggregation operations. One such method is Aggregate.prototype.exec()
, which allows you to execute an aggregation pipeline and return a promise or use a callback to handle the results. This article will explain how to use the exec()
method effectively in your Mongoose applications, helping you fetch and manipulate data with ease.
What is the exec() Method in Mongoose Aggregation?
The exec()
method in Mongoose’s aggregation API executes the aggregation pipeline on the current model, either returning a promise (for async/await) or accepting a callback function to handle the result. This gives you flexibility in managing database queries, making it easy to handle asynchronous tasks.
Syntax:
aggregate.exec( callback )
- callback: A function that handles the result of the aggregation. If not provided, the exec() method returns a promise, which can be handled using then() or async/await.
Parameters
callback: The callback function receives two parameters:
- error: Error object if any occurs during aggregation.
- result: The resulting array from the aggregation query.
Return Value:
- With Callback: The callback is invoked with two parameters,
error
and result
. - With Promise: If no callback is provided,
exec()
returns a promise that resolves with the aggregation result or rejects with an error.
Setting up Node.js Application
To set up the Mongoose aggregation pipeline with exec(), follow these steps:
Step 1: Create a Node.js application
Run the following command in your terminal
npm init
Step 2: Install Mongoose
After creating the NodeJS application, Install the required module using the following command:
npm install mongoose
Step 3: Structure of Your Project
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 exec() with a Callback
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
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([{ $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: Using exec() with async/await
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
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);
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 ' }
]
Why Use exec()
?
The exec()
method provides flexibility in how you handle results from the aggregation pipeline. It allows you to:
- Handle Results Asynchronously: With promises and
async/await
, exec()
makes handling complex queries simpler and more readable. - Error Handling: Easily manage errors in aggregation queries by using callback functions or try-catch blocks in async functions.
- Code Clarity: The explicit handling of callback functions or promises improves code maintainability and readability.
When to Use exec()
?
You should use exec()
in the following cases:
- When you want to execute an aggregation pipeline and handle results asynchronously using callback functions or async/await.
- When you need to optimize database queries and want to improve readability and maintainability.
- When you are building applications that need to execute complex MongoDB queries or perform aggregation tasks like sorting, grouping, or filtering.
Conclusion
Mongoose’s aggregate.exec()
method is an essential tool for executing aggregation pipelines and handling results efficiently. Whether you prefer using callback functions or async/await
, this method provides a flexible and easy-to-understand way to interact with MongoDB aggregation results. By using exec()
, you can easily handle complex aggregation tasks and improve the performance and scalability of your Node.js applications.