Open In App

Mongoose Aggregate Aggregate() API

Last Updated : 26 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The Mongoose Aggregate API Aggregate() method of the Mongoose API is used to perform aggregation tasks. It allows us to create an aggregation pipeline. The aggregation constructor is used for building and configuring aggregation pipeline. It is recommended not to instantiate the Aggregation class directly instead we can use it on any model we have defined over mongoose schema. Let us understand the aggregate() method using an example.

Syntax:

Model.aggregate( <pipeline>, <model>);

Parameters: This method accepts two parameters as described below:

  • pipeline: It is used to specify the pipeline array of objects.
  • model: It is used to determine the model’s name with which we will use the aggregate pipeline.

Return Value: This method returns the result set in the form of an object array based on the aggregation pipeline.

Setting up Node.js Mongoose Module:

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: In this example, we have established a database connection using mongoose and defined a model over studentSchema. In the end, we are using the aggregate() method on the mongoose model and configuring the pipeline. 

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
  
const connectionObject = mongoose.createConnection(URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const studentSchema = new mongoose.Schema({
    name: { type: String },
    age: { type: Number },
    rollNumber: { type: Number },
});
  
const Student = connectionObject.model('Student', studentSchema);
  
Student.aggregate([{ $project: { name: 1, rollNumber: 1,
    _id: 0 } }]).exec((error, resultSet) => {
    if (error) {
        console.log(error);
    } else {
        console.log(resultSet);
    }
})


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: 'Student1', rollNumber: 9 },
      { name: 'Student3', rollNumber: 178 },
      { name: 'Student4', rollNumber: 152 },
      { name: 'Student2', rollNumber: 176 }
]

Example 2:  The below example illustrates the functionality of the Mongoose API Aggregate, using then and catch block.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
  
const connectionObject = mongoose.createConnection(URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const studentSchema = new mongoose.Schema({
    name: { type: String },
    age: { type: Number },
    rollNumber: { type: Number },
});
  
const Student = connectionObject.model('Student', studentSchema);
  
Student.aggregate().project({ age: 1 }).then(resultSet => {
    console.log(resultSet);
}).catch(error => console.log(error));


Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

[
    { _id: new ObjectId("63a40a1065e8951038a391b1"), age: 20 },
      { _id: new ObjectId("63a4a98407370cdcd1961b1a"), age: 19 },
      { _id: new ObjectId("63a4a99307370cdcd1961b1d"), age: 24 },
      { _id: new ObjectId("63a4a9a207370cdcd1961b2c"), age: 18 }
]

Reference: https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads