Open In App

How to use $group for a MongoDB query in Node.js ?

Improve
Improve
Like Article
Like
Save
Share
Report

The $group operator is an aggregation operator or an aggregation stage, which groups multiple data or documents by some specified expression and combines them into a single document.

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 which aggregation performs.

Syntax: $group operator 

{
    $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.

Install Mongoose:

Step 1: You can visit the link Install mongoose to install the mongoose module. You can install this package by using this command.

npm install mongoose

Step 2: Now you can import the mongoose module in your file using:

const mongoose = require('mongoose');

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 GFG

Creating a Node application:

Step 1: Create package.json using the following command:

npm init

Step 2: Create file main.js with the following code.

Filename: main.js

Javascript




// 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)
    })


Run main.js using the command:

node main.js

Output: In the console, we are getting documents grouped by department and computed fields totalEmployee and averageSalary in each group.

Output after executing main.js

Explanation: 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.



Last Updated : 01 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads