How to Perform Aggregation Operations in MongoDB using Node.js?
Last Updated :
27 Jun, 2024
Aggregation operations in MongoDB allow you to process data records and return computed results. These operations group values from multiple documents, and perform a variety of operations on the grouped data to return a single result. MongoDB's aggregation framework is powerful and flexible, enabling data analysis, transformation, and complex queries.
In this article, we'll explore how to perform aggregation operations in MongoDB using Node.js. We'll cover various aggregation approaches, provide step-by-step instructions to set up the application and illustrate with examples.
In MongoDB, the primary way to perform aggregation is through the aggregate method. This method can be used with various stages like $match, $group, $sort, $project, and many others to process the documents in the collection.
Common Aggregation Stages in MongoDB
- $match: Filters the documents to pass only those that match the specified condition(s).
- $group: Groups input documents by a specified identifier expression and apply the accumulator expressions.
- $sort: Sorts the documents.
- $project: Reshapes each document in the stream, such as by adding, removing, or renaming fields.
1. $match
The $match stage filters documents to pass only those that match the specified condition(s).
Syntax:
db.collection.aggregate([ { $match: { <condition> } }])
Example:
JavaScript
db.users.aggregate([
{ $match: { age: { $gte: 21 } } }
])
2. $group
The $group stage groups input documents by a specified identifier expression and applies the accumulator expressions.
Syntax:
db.collection.aggregate([ { $group: { _id: <expression>, <field1>: { <accumulator1>: <expression1> }, ... } }])
Example:
JavaScript
db.orders.aggregate([
{ $group: { _id: "$customerId", totalAmount: { $sum: "$amount" } } }
])
3. $sort
The $sort stage sorts all input documents and returns them in sorted order.
Syntax:
db.collection.aggregate([ { $sort: { <field1>: <sortOrder>, ... } }])
Example:
JavaScript
db.products.aggregate([
{ $sort: { price: -1 } }
])
4. $project
The $project stage reshapes each document in the stream, such as by adding, removing, or renaming fields.
Syntax:
db.collection.aggregate([ { $project: { <field1>: <expression1>, ... } }])
Example: To show
JavaScript
db.users.aggregate([
{ $project: { name: 1, age: 1, _id: 0 } }
])
Steps to Create Application
To create a Node.js application that uses MongoDB's aggregation framework, follow these steps:
Step 1. Initialize Node.js Application
First, create a new directory for your application and initialize a new Node.js project.
mkdir mongo-aggregation
cd mongo-aggregation
npm init -y
Step 2. Install Required Modules
Install the mongodb package, which is the official MongoDB driver for Node.js.
npm install mongodb
Updated Dependencies:
"dependencies": {
"mongodb": "^6.6.2",
}
Example: To demonstrate creating a Node.js application that uses MongoDB's aggregation framework.
Node
// insertData.js
const { MongoClient } = require("mongodb");
async function insertSampleData() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db("testdb");
const collection = database.collection("users");
const sampleData = [
{ name: "Alice", age: 25, city: "New York" },
{ name: "Bob", age: 30, city: "San Francisco" },
{ name: "Charlie", age: 25, city: "New York" },
{ name: "David", age: 30, city: "San Francisco" },
{ name: "Edward", age: 35, city: "Los Angeles" },
];
await collection.insertMany(sampleData);
console.log("Sample data inserted successfully");
} finally {
await client.close();
}
}
insertSampleData().catch(console.error);
Node
// index.js
const { MongoClient } = require("mongodb");
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db("testdb");
const collection = database.collection("users");
// Example Aggregation: Group users by age and
// count the number of users in each age group
const aggregationPipeline = [
{ $group: { _id: "$age", count: { $sum: 1 } } },
];
const results = await collection.aggregate(aggregationPipeline).toArray();
console.log("Aggregation results:", results);
} finally {
await client.close();
}
}
main().catch(console.error);
Output:
Output
Similar Reads
How to Perform a findOne Operation in MongoDB using Node.js?
The findOne operation in MongoDB is used to get a single document from the collection if the given query matches the collection record. While using findOne, if more than one record is there with the exact same match, then it will return the very first one. We will use this operation if we need to fe
4 min read
How To Perform a Find Operation With Sorting In MongoDB Using Node.js?
Performing a find operation with sorting in MongoDB using Node.js is a common task for developers working with databases. This guide will walk you through the process step-by-step, including setting up a MongoDB database, connecting to it using Node.js, performing a find operation, and sorting the r
3 min read
How to Perform a Find Operation with Limit and Skip in MongoDB using Node.js?
In MongoDB, the find operation is used to query the database and retrieve documents that match a specified criterion. Using limit and skip along with find allows for efficient pagination of results. limit specifies the maximum number of documents to return, while skip specifies the number of documen
3 min read
How to Perform Find Operation With Projection in MongoDB Using NodeJS?
MongoDB's find() method can be used to query the documents from the collection. Protection in MongoDB allows you to select the fields to return in the query results which can be useful for improving the performance and reducing the amount of the data transferred over the network. In this article, we
5 min read
How to Perform Geospatial Queries in MongoDB using Node.js?
A geospatial query involves searching for data based on geographic locations. It allows developers to identify and analyze data associated with specific coordinates or within a defined proximity of a given point. In a geospatial query, we can define a geographic shape, such as a point, line, or poly
6 min read
How to add range in the Collection of Mongodb using Node.js ?
Mongoose.module is one of the most powerful external module of the node.js.Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server.Mongoose module provides several functions in order to manipulate the documen
2 min read
How to Handle Errors in MongoDB Operations using NodeJS?
Handling errors in MongoDB operations is important for maintaining the stability and reliability of our Node.js application. Whether we're working with CRUD operations, establishing database connections, or executing complex queries, unexpected errors can arise. Without proper error handling, these
8 min read
How to add Timestamp in Mongodb Collection using Node.js ?
Timestamp: With the help of timestamp document in the collection of the MongoDB can be differentiated on the basis of time. We can add Timestamp in Mongodb Collection in Node.js using the following approach: Installing Module: Install the mongoose module using the following command: npm install mong
1 min read
CRUD Operations and File Upload using Node.js and MongoDB
Within the computer programming world, CRUD is an elision for the 4 operations Create, Read, Update, and Delete. Create, Read, Update, and Delete (CRUD) are the four basic functions that models should be able to do, at most. In RESTful applications, CRUD often corresponds to the HTTP methods like  P
15 min read
How to Join Two Collections in Mongodb using Node.js ?
Joining two collections in MongoDB using Node.js can be accomplished using the aggregation framework. The $lookup stage in the aggregation pipeline allows you to perform a left outer join to another collection in the same database. Understanding MongoDB CollectionsIn MongoDB, a collection is a group
4 min read