Open In App

Mongoose Aggregate.prototype.project() API

Improve
Improve
Like Article
Like
Save
Share
Report

The Aggregate API.prototype.project() method of the Mongoose API is used to perform aggregation tasks. It allows us to select fields from the collection. Using this method we can request for selected fields to be extracted from the collection to the result set. If you do not want all fields from the collection in the result set, you can use project() to request for the specified fields to be included in the result set. Overall, we can specify inclusive and exclusive fields for our result set.

 Syntax:

aggregate().project( specifications )

Parameters: This method accepts a single parameter as described below:

  • Object/String: It is used to specify the fields you want to include and exclude in/from the result set. 

Return Value: This method returns the result set in the form of an array.

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 model over userSchema, having three columns or fields “_id”, “name”, and “bornYear”. At the end, we are calling project() method by passing specification in the form of object. In this example, we want _id and name to be included in result set. That’s why we set the value for both of them as 1. If you do not want any field to be included in result set either you do not mention it in specifications or assign 0 as a value to that field.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const userSchema = new mongoose.Schema({
    name: String,
    bornYear: Number
});
  
const User = mongoose.model('User', userSchema);
  
User.aggregate()
    .project({ _id: 1, name: 1 })
    .then((result, error) => {
        if (result)
            console.log(result);
        else
            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("6387aa99c92df30f995e8309"), name: 'Aakash' },  
  { _id: new ObjectId("6387aa99c92df30f995e830a"), name: 'Ayush' },   
  { _id: new ObjectId("6387aa99c92df30f995e830b"), name: 'Rahul' },   
  { _id: new ObjectId("6387aa99c92df30f995e830c"), name: 'Mivan' },   
  { _id: new ObjectId("6387aa99c92df30f995e830d"), name: 'Sidiksha' },
  { _id: new ObjectId("6387aa99c92df30f995e830e"), name: 'Takshwi' }, 
  { _id: new ObjectId("6387aa99c92df30f995e830f"), name: 'Kashwi' },  
  { _id: new ObjectId("6387aa99c92df30f995e8310"), name: 'Kinjal' }   
]

Example 2: In this example, we have established a database connection using mongoose and defined model over userSchema, having three columns or fields “_id”, “name”, and “bornYear”, we are calling aggregate() method on User model. In this example, we just want the bornYear field to be included in result set. That is why we have assigned 1 to bornYear field and 0 to _id. We have not mentioned name field so it will automatically be considered exclusive from result set.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const userSchema = new mongoose.Schema({
    name: String,
    bornYear: Number
});
  
const User = mongoose.model('User', userSchema);
  
User.aggregate([{ $project: { _id: 0, bornYear: 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:

[
  { bornYear: 2000 },
  { bornYear: 2000 },
  { bornYear: 2000 },
  { bornYear: 2019 },
  { bornYear: 2019 },
  { bornYear: 2018 },
  { bornYear: 2021 },
  { bornYear: 2021 } 
]

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



Last Updated : 06 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads