Understanding the Mongoose aggregate().then() Method
Last Updated :
16 May, 2025
In Mongoose, the aggregate()
method is a powerful tool used for performing aggregation tasks on MongoDB collections. It allows you to process and transform data in various ways. The then()
method is used to handle the promise returned by the aggregate()
method, enabling you to manage asynchronous operations effectively. In this article, we'll break down how to use aggregate().then()
with detailed examples and explain its role in Mongoose aggregations.
What is Mongoose aggregate()
?
Mongoose's aggregate()
method provides a way to perform complex data manipulations such as filtering, grouping, sorting, and reshaping documents directly within MongoDB using the aggregation framework. However, working with aggregate()
typically returns a promise, which is where the then()
method comes in.
Syntax:
aggregate().then(successCallback, errorCallback)
Parameters:
- successCallback: It is the callback function that will execute if the promise is resolved.
- errorCallback: It is the callback function that will execute if the promise is rejected.
Why Use aggregate().then()
?
Using aggregate().then()
ensures that:
- You can manage asynchronous operations smoothly.
- You can handle both successful and failed aggregation results with clean and readable code.
- It provides an easier way to work with the results of aggregations, especially when you need to perform subsequent actions or error handling.
Setting Up a Mongoose Aggregation Example
Let’s walk through a practical example where we connect to a MongoDB database and use Mongoose's aggregate()
method with then()
.
Step 1: Create a Node.js Application
npm init
Step 2: Install Mongoose
npm install mongoose
Step 3: Define the Project Structure
Create a file named app.js
. We will create a simple aggregation pipeline to fetch data from a MongoDB database.
Database Structure: The database structure will look like this, the following documents are present in the collection.
Example 1: Simple Aggregation with then()
In this example, We have established a database connection using mongoose and defined a model over userSchema, having three columns or fields "_id", "name", and "age". At the end, we are calling aggregate method on User model and handing returned promise using then() method.
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 userSchema = new mongoose.Schema({
_id: Number,
name: String,
age: Number
});
const User = mongoose.model('User', userSchema);
User.aggregate([{ $project: { _id: 1, name: 1, age: 1 } }])
.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: 1, name: 'Virat Kohli', age: 32 },
{ _id: 2, name: 'David Warner', age: 35 },
{ _id: 3, name: 'Ben Stokes', age: 38 }
]
Explanation:
aggregate()
: Performs an aggregation on the User
collection.then()
: Handles the promise returned by the aggregate()
method. If the aggregation is successful, the successCallback
logs the result. If an error occurs, the errorCallback
logs the error.
Example 2: Using aggregate().then()
for Student Collection
In this example, We have established a database connection using mongoose and defined model over studentSchema, having two columns or fields "name", and "rollNumber". At the end, we are calling aggregate method on User model and storing result in a variable named agg and calling then() method on agg to handle the promise.
Database Structure:
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 studentSchema = new mongoose.Schema({
name: String,
rollNumber: Number
});
const Student = mongoose.model('Student', studentSchema);
const agg = Student.aggregate([
{ $project: { name: 1, rollNumber: 1 } }])
agg.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: new ObjectId("63879b6e636d0979693c29f5"),
name: 'Aakash',
rollNumber: 101
},
{
_id: new ObjectId("63879b6e636d0979693c29f6"),
name: 'Rahul',
rollNumber: 102
}
]
Important Notes on aggregate().then()
- Asynchronous Execution: Since MongoDB operations like aggregation are asynchronous, using
then()
helps manage this asynchrony. - Promise Handling: The
then()
method returns a promise, which is essential for handling data once the aggregation task is complete. - Error Handling: The
catch()
block is often used in conjunction with then()
for robust error handling.
Conclusion
The Mongoose aggregate().then()
method is a powerful tool for performing aggregation tasks while allowing you to manage the results asynchronously. By using promises, you can handle data transformations and error handling in a cleaner and more efficient manner. Whether you’re working with a simple aggregation or a complex pipeline, understanding how to use then()
with aggregate()
ensures your application can handle data processing smoothly.