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.