How to use $group for a MongoDB query in Node.js ?
Last Updated :
15 Jul, 2024
The $group
stage in MongoDB's aggregation framework is a powerful tool for grouping documents by a specified field and performing various operations on the grouped data, such as calculating totals, averages, and other aggregates. When combined with Node.js, this allows for efficient data processing and analysis within your application. This article will guide you through the process of using $group
in MongoDB queries with Node.js.
$group Operator
The $group
operator in MongoDB is used in the aggregation pipeline to group documents by a specified key and perform aggregate operations, such as sum, count, or average, on grouped data. It allows for sophisticated data transformation and computation within collections.
Aggregation in MongoDB is an operation that groups values from multiple documents together and can perform a variety of operations on the grouped data to return a single result. And $group is one of the operations that aggregation performs.
Syntax:
{
$group:
{
_id: <expression>,
<field>: { <accumulator> : <expression> }
}
}
- _id: It is the field by which you want to group the documents.
- field: It is an optional parameter, and it is the computed field after performing certain accumulator operations on the grouped data.
Approach
To use $group
in a MongoDB query with Node.js:
- Connect to MongoDB using Mongoose or native driver.
- Define aggregation pipeline stages, including
$group
for grouping documents. - Execute aggregation using
.aggregate()
method on the collection. - Handle results or errors in the callback or promise chain.
Installation Steps
Step 1: Make a folder structure for the project.
mkdir myapp
Step 2: Navigate to the project directory
cd myapp
Step 3: Initialize the NodeJs project inside the myapp folder.
npm init -y
Step 3: Install the necessary packages/libraries in your project using the following commands.
npm install mongoose
Project Structure:

The updated dependencies in package.json file will look like:
"dependencies": {
"express": "^8.4.4",
}
Database
We have already created a collection named employees in our database GFG with the following entries show in the image below:
Collection employees in the database GFGExample: Implementation to show the use of $group for a MongoDB query in NodeJS.
JavaScript
// app.js
// Requiring module
const mongoose = require('mongoose');
// Connecting to database
mongoose.connect('mongodb://localhost:27017/GFG',
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
});
// Schema of employee collection
const employeeSchema = new mongoose.Schema({
name: String,
city: String,
salary: Number,
department: String
})
// Model of employees collection
const Employee = mongoose.model(
'employee', employeeSchema)
// Group employees by department field
// and computing total no. of employees
// and average salary in each department
Employee.aggregate([
{
$group:
{
_id: { department: "$department" },
totalEmployee: { $sum: 1 },
averageSalary: { $avg: "$salary" }
}
}
])
.then(result => {
console.log(result)
})
.catch(error => {
console.log(error)
})
Step to Run Application: Run the application using the following command from the root directory of the project
node app.js
Output: In the console, we are getting documents grouped by department and computed fields totalEmployee and averageSalary in each group.Here we have grouped employees by department field and computing separate fields totalEmployee which contains the total number of employees in each group and averageSalary which gives the average salary of employees in each group, using accumulation operators $sum and $avg.
Output after executing main.js
Similar Reads
How To Query For Documents In MongoDB Using NodeJS?
MongoDB is the popular NoSQL database that allows for flexible and scalable data storage. NodeJS and JavaScript runtime built on Chrome's V8 JavaScript engine. It is often used with MongoDB to build powerful and efficient applications. In this article, we will guide you on how to query the documents
4 min read
How to drop collection in MongoDb using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
2 min read
How to Get Data from MongoDB using Node.js?
One can create a simple Node.js application that allows us to get data to a MongoDB database. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. Also, we use the EJS for our front end to render the simple HTML form and a table to show the data. Prerequisi
6 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 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. Inst
1 min read
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 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 Make a Synchronous MongoDB Query in NodeJS?
MongoDB is a popular NoSQL database that is often used in modern web development. It is known for its flexibility, scalability, and ease of use. Node.js, with its non-blocking, event-driven architecture, is a natural fit for MongoDB. However, working with asynchronous code can sometimes be challengi
2 min read
How to Retrieve Data from MongoDB Using NodeJS?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for the storage and retrieval of data. Thi
3 min read
How to Use MongoDB Transactions in Node.js?
Using MongoDB transactions in Node.js involves several steps. Transactions allow multiple operations on the database to be executed in an all-or-nothing manner, ensuring data consistency. we will learn how to use MongoDB transaction in Node.js.PrerequisitesMongoDB (Version 4.0 or higher Recommended)
2 min read