Mongoose Aggregate.prototype.project() API
Last Updated :
08 Apr, 2025
Mongoose, a popular Object Data Modeling (ODM) library for MongoDB and Node.js, provides a powerful aggregation framework that allows developers to efficiently process and manipulate data.
One of the key methods in this framework is the project()
method, which is part of the aggregation pipeline. The project()
method enables us to control which fields from a document should be included or excluded in the results of an aggregation query.
What is Aggregate.prototype.project()
in Mongoose?
The project()
method in Mongoose is used to shape the output of an aggregation query by specifying which fields should be included or excluded in the result set. This is crucial when we want to minimize the amount of data returned from a query or when we need to exclude sensitive fields like the document's _id
.
Syntax:
aggregate().project( specifications )
- specifications: An object that defines the fields to include or exclude in the result. We can use
1
for including fields and 0
for excluding fields.
Parameters:
- Object/String: The specifications object is used to define which fields to include (
1
) or exclude (0
) from the result set.
Return Value:
- The
project()
method returns an array containing the documents that match the aggregation pipeline, but with the fields specified in the specifications
object.
How to Use Aggregate.prototype.project()
in Mongoose
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: Including Specific Fields in the Result Set
In this example, we establish a database connection using mongoose and define a model based on userSchema. Schema 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 we do not want any field to be included in result set either we do not mention it in specifications or assign 0 as a value to that field.
Filename: app.js
// Require mongoose module
const mongoose = require("mongoose");
// Set Up the Database connection
mongoose.connect("mongodb://localhost:27017/geeksforgeeks", {
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' }
]
Explanation: In this example, we have only included the name
and _id
fields in the output. The bornYear
field is not included because it was not specified in the project()
method.
Example 2: Excluding Specific Fields from the Result Set
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 is automatically excluded from the result set.
Filename: app.js
// Require mongoose module
const mongoose = require("mongoose");
// Set Up the Database connection
mongoose.connect("mongodb://localhost:27017/geeksforgeeks", {
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 }
]
Explanation: In this case, we only include the bornYear
field in the output, while the _id
and name
fields are excluded.
Advanced Usage: Combining project() with Other Stages
We can also combine the project()
stage with other aggregation stages, such as $match
, $sort
, or $group
, to perform more complex queries. In the following example, we will filter the documents to include only those with a bornYear
greater than or equal to 2000, including only the name
field (excluding _id
), and sort the results by the name
field in ascending order.
Example:
User.aggregate([
{ $match: { bornYear: { $gte: 2000 } } }, // Filter by bornYear
{ $project: { name: 1, _id: 0 } }, // Include only name, exclude _id
{ $sort: { name: 1 } } // Sort by name in ascending order
]).exec((error, result) => {
if (error) {
console.log(error);
} else {
console.log(result);
}
});
Output:
[
{ name: 'Ayush' },
{ name: 'Kashwi' },
{ name: 'Kinjal' },
{ name: 'Mivan' },
{ name: 'Rahul' },
{ name: 'Sidiksha' },
{ name: 'Takshwi' },
{ name: 'Aakash' }
]
Conclusion
The Aggregate.prototype.project()
method in Mongoose provides a flexible and powerful way to control the fields returned in an aggregation result. By using this method, we can include only the necessary fields, improving performance and simplifying your query results. By combining project()
with other stages like $match
, $sort
, and $group
, we can create more advanced queries that meets specific requirements in our application. Whether we want to include, exclude, or reshape the data, the project()
method is a valuable tool in our Mongoose aggregation toolkit.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read