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 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 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 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 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
How to Perform Data Migration in MongoDB using Node.js?
In this article, we migrate existing data from the sourced database (MongoDB) to the destination database (MongoDB) using Node.js. To perform the whole operation, we will first insert documents into the sourced database and then migrate to the destination. Approach to Perform Data Migration in Mongo
3 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
How to replace one document in MongoDB using Node.js ?
MongoDB, the most popular NoSQL database, we can count the number of documents in MongoDB Collection using the MongoDB collection.countDocuments() function. The mongodb module is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. Insta
1 min read
How to use the $lookup operator in aggregation pipelines in MongoDB?
One of the essential stages of the Aggregation Pipeline is the $lookup. It enables us to accomplish a left outer join between two collections. This step is quite beneficial when we have to compose data from different collections into a single document. The Aggregation Pipeline in MongoDB is a robust
4 min read
How to Perform Text Search in MongoDB using Node.js?
MongoDB is an open-source, cross-platform, No-SQL database that stores data in documents, which contain data in the form of key-value pairs. In this article, we will learn about how to perform text-based searches in MongoDB using node.js. Prerequisites Node.jsMongoDBMongoDB Atlas Connect with Applic
5 min read