Open In App

Mongoose Model.aggregate() API

Last Updated : 20 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Mongoose Model API Model.aggregate() method of the Mongoose API is used on the Document model. It allows to perform aggregation tasks on the models collection. Using this method we can execute aggregation operation on mongoose models. We can directly call this method on model. Let us understand the aggregate() method using an example.

Syntax:

Model.aggregate( pipeline, options, callback );

Parameters: This method accepts three parameters as discussed below:

  • pipeline: It is used to specify the aggregation pipeline operations.
  • options: It is used to configure various properties.
  • callback: It is used to configure the callback function to handle the returned promise.

Return Value: This method returns the aggregate object on which we can call callback function or we can handle that using then or catch block.

Setting up Node.js application:

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 are illustrating the functionality of aggregate() method. Using the aggregation pipeline we are selecting name and orderNumber to be visible in the result set.

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 Customer = connectionObject.model(
    "Customer",
    new mongoose.Schema({
        name: String,
        address: String,
        orderNumber: Number,
    })
);
  
Customer.aggregate().project(
    { name: 1, _id: 0, orderNumber: 1 }
).exec((error, result) => {
    if (error) {
        console.log(error);
    } else {
        console.log(result);
    }
})


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: 'Chintu', orderNumber: 9 },  
  { name: 'Aditya', orderNumber: 20 }, 
  { name: 'Bhavesh', orderNumber: 65 },
  { name: 'Mivaan', orderNumber: 9 },  
  { name: 'Takshwi', orderNumber: 15 },
  { name: 'Kinjal', orderNumber: 35 }  
]

Example 2: In this example, we are illustrating the functionality of aggregate() method. Using the aggregation pipeline we are sorting the result set on orderNumber field in ascending order.

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 Customer = connectionObject.model(
    "Customer",
    new mongoose.Schema({
        name: String,
        address: String,
        orderNumber: Number,
    })
);
  
Customer.aggregate([
    { $sort: { orderNumber: 1 } },
    { $project: { name: 1, _id: 0, orderNumber: 1 } }
]).then(result => {
    console.log(result);
}).catch(err => {
    console.log(err);
})


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: 'Chintu', orderNumber: 9 },  
  { name: 'Mivaan', orderNumber: 9 },  
  { name: 'Takshwi', orderNumber: 15 },
  { name: 'Aditya', orderNumber: 20 }, 
  { name: 'Kinjal', orderNumber: 35 }, 
  { name: 'Bhavesh', orderNumber: 65 } 
]

Reference: https://mongoosejs.com/docs/api/model.html#model_Model-aggregate



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads