Open In App

Mongoose Model.aggregate() API

Last Updated : 08 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Mongoose, a popular ODM (Object Data Modeling) library for MongoDB and Node.js, provides an easy-to-use API for interacting with MongoDB databases. One of the most powerful features of Mongoose is the aggregate() method.

In this article, we will expalin the aggregate() method, explain its syntax, usage, and provide code examples that demonstrate how to utilize this method to perform complex queries such as sorting, grouping, filtering, and projections.

What is Model.aggregate() in Mongoose?

The aggregate() function in Mongoose is used to perform data aggregation operations on a MongoDB collection. It utilizes MongoDB’s aggregation framework, allowing us to process and transform data in sophisticated ways. This method allow developers to perform advanced data processing tasks on collections using MongoDB’s aggregation pipeline.

Syntax:

Model.aggregate( pipeline, options, callback );

Parameters:

  • pipeline: It is used to specify the aggregation pipeline operations.
  • options: It is used to configure various properties.
  • callback: It is used to configure the callback function to handle the returned promise.

Return Value:

This method returns the aggregate object on which we can call callback function or we can handle that using then or catch block.

Key Features of Model.aggregate()

1. Aggregation Pipeline: The aggregation pipeline is a series of stages, each performing a specific operation on the data (e.g., $match, $group, $sort, $project).

2. Powerful Data Transformations: It allows for operations like filtering, sorting, and grouping, which can’t be achieved using simple find() queries.

3. Enhanced Performance: MongoDB handles the data aggregation operations efficiently within the database engine, reducing the need to pull excessive data into the application layer.

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: Selecting Specific Fields Using $project

In this example, we are illustrating the functionality of aggregate() method. Using the aggregation pipeline we are selecting name and orderNumber to be visible in the result set.

Filename: app.js

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

// Set Up the Database connection
const URI = "mongodb://localhost:27017/geeksforgeeks";

const connectionObject = mongoose.createConnection(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});

const Customer = connectionObject.model(
"Customer",
new mongoose.Schema({
name: String,
address: String,
orderNumber: Number,
})
);

Customer.aggregate().project(
{ name: 1, _id: 0, orderNumber: 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:

[
{ name: 'Chintu', orderNumber: 9 },
{ name: 'Aditya', orderNumber: 20 },
{ name: 'Bhavesh', orderNumber: 65 },
{ name: 'Mivaan', orderNumber: 9 },
{ name: 'Takshwi', orderNumber: 15 },
{ name: 'Kinjal', orderNumber: 35 }
]

Example 2: Sorting the Result Set Using $sort

In this example, we are illustrating the functionality of aggregate() method. Using the aggregation pipeline we are sorting the result set on orderNumber field in ascending order.

Filename: app.js

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

// Set Up the Database connection
const URI = "mongodb://localhost:27017/geeksforgeeks";

const connectionObject = mongoose.createConnection(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});

const Customer = connectionObject.model(
"Customer",
new mongoose.Schema({
name: String,
address: String,
orderNumber: Number,
})
);

Customer.aggregate([
{ $sort: { orderNumber: 1 } },
{ $project: { name: 1, _id: 0, orderNumber: 1 } }
]).then(result => {
console.log(result);
}).catch(err => {
console.log(err);
})

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: 'Chintu', orderNumber: 9 },
{ name: 'Mivaan', orderNumber: 9 },
{ name: 'Takshwi', orderNumber: 15 },
{ name: 'Aditya', orderNumber: 20 },
{ name: 'Kinjal', orderNumber: 35 },
{ name: 'Bhavesh', orderNumber: 65 }
]

Conclusion

The Mongoose aggregate() method is an essential tool for performing complex data manipulations in MongoDB. It allows developers to utilize the full power of MongoDB’s aggregation framework to transform and process data efficiently at the database level. Whether we need to filter, group, sort, or project data, aggregate() provides an elegant and scalable solution. With its powerful capabilities, aggregate() can significantly improve performance and simplify data processing tasks in large-scale applications.



Next Article

Similar Reads