MongoDB Projection
MongoDB is a powerful NoSQL database that allows flexible data storage and retrieval. When dealing with large documents or collections, it becomes crucial to retrieve only the necessary data, especially when working with large-scale applications.
MongoDB’s projection feature allows us to do just that by selecting specific fields from the document, reducing the amount of unnecessary data fetched and improving query performance.
This article explains the concept of MongoDB projection, how to use it effectively with the find()
method, and various examples to help you understand its power and importance in optimizing database queries.
What is MongoDB Projection?
MongoDB projection is the process of selecting only the specific fields we want to retrieve from a document rather than fetching the entire document. By limiting the amount of data, projection helps improve performance, reduces memory usage, and makes our queries more efficient.
Consider the following example of an employee document in MongoDB:
{
name: "Roma",
age: 30,
branch: EEE,
department: "HR",
salary: 20000
}
If we want to fetch only the name and age of the employee, projection allows us to do this without retrieving the entire document, which could be wasteful if the document contains many other fields.
In MongoDB, we use projection with the db.collection.find()
method. The second parameter in this method specifies the projection object. This object defines which fields should be included or excluded from the result. The syntax is as follows:
Syntax:
db.collection.find({}, {field1: value2, field2: value2, ..})
Key Terms
query
: Defines the selection criteria (similar to a WHERE clause in SQL).projection
: Defines which fields you want to include or exclude in the result.
Projection Values
- 1 or true: Indicates the field should be included in the returned documents.
- 0 or false: Indicates the field should be excluded from the returned documents.
Default Behavior with _id
By default, MongoDB always includes the _id
field in the result unless explicitly excluded. If we don't want the _id
field in the output, we can set it to 0
in the projection
Examples of Using MongoDB Projection
In the following examples, we are working with:
Database: GeeksforGeeks
Collection: employee
Document: five documents that contain the details of the employees in the form of field-value pairs.
We will now explore several MongoDB projection examples that demonstrate how to selectively retrieve specific fields from these documents

1. Displaying Only Specific Fields
Suppose we have an employee collection, and we want to display only the name and age fields of the employees. We can do this with projection as shown below:
Query:
db.employee.find({}, {name: 1, age: 1})
Output:

Explanation:
- The empty curly braces
{}
represent the query condition, meaning you are not filtering any documents (i.e., you want all the documents). {name: 1, age: 1}
is the projection object, where1
means that you want to include thename
andage
fields in the result
2. Displaying the names of the employees without the _id
field
If we want to display all fields except the _id
field, we can do so by explicitly setting _id
to 0
:
Query:
db.employee.find({}, {name: 1, age: 1, _id: 0})
Output:

Explanation
: {_id: 0}
ensures the _id
field is excluded from the result.
3. Displaying the name and the department of the employees without the _id
field
To display the name and department of the employees without the _id
field, we can use the following MongoDB qu ery with projection:
Query:
db.employee.find({}, {name: 1, department: 1, _id: 0})
Output:

Explanation:
- The empty
{}
in the first parameter represents the query condition, meaning you are selecting all the documents from the collection - This will return documents with only the
name
anddepartment
fields for each employee, without the_id
field.
4. Displaying the names and the department of the employees whose joining year is 2018
We can combine projection with a query filter to fetch specific documents. For example, if we want to fetch employees who joined in 2018 and display only their name
and department
, we would write:
Query:
db.employee.find({joiningYear: 2018}, {name: 1, department: 1, _id: 0})
Output:

Explanation:
{joiningYear: 2018}
is the filter that selects employees who joined in 2018.{name: 1, department: 1, _id: 0}
specifies the fields we want to include, excluding_id
.
MongoDB Projection Operators
MongoDB also provides certain projection operators that we can use to modify how fields are returned. These operators allow for more advanced selection and reshaping of data. However, it's important to note that the find()
method does not support all projection operators. Some of the projection operators that are not supported include $
, $elemMatch
, $slice
, and $meta
.
1. $slice Operator
The $slice
operator is useful when dealing with array fields. It allows us to return a subset of an array, such as the first few elements, a specific range, or even the last few elements. While $slice
is supported in aggregation pipelines, it is not allowed in the find()
projection.
Example: If we have a document like this:
{
name: "John",
skills: ["JavaScript", "MongoDB", "Node.js", "CSS"]
}
We can use $slice
in the aggregation pipeline to return only the first 2 skills:
db.employee.aggregate([
{ $project: { skills: { $slice: [0, 2] } } }
])
Output:
{
name: "John",
skills: ["JavaScript", "MongoDB"]
}
2. $elemMatch Operator
The $elemMatch
operator is used to retrieve specific elements from an array field that match certain conditions. This is especially useful when you have an array of embedded documents or objects, and you only want to return the elements that meet specific criteria. Like $slice
, $elemMatch
is supported in the aggregation pipeline but not in the find()
method's projection.
Example: Suppose you have a document with a skills
array of embedded documents, and you want to return only the skills that have a level
greater than 3.
{
name: "John",
skills: [
{ name: "JavaScript", level: 5 },
{ name: "MongoDB", level: 3 },
{ name: "Node.js", level: 4 }
]
}
We can use $elemMatch
in the aggregation pipeline to select only the skills where the level
is greater than 3:
db.employee.aggregate([
{ $project: { skills: { $elemMatch: { level: { $gt: 3 } } } } }
])
Output:
{
name: "John",
skills: [
{ name: "JavaScript", level: 5 },
{ name: "Node.js", level: 4 }
]
}
Using MongoDB Projection in Aggregation Pipeline
In MongoDB, the aggregation pipeline provides more advanced ways to project fields and reshape documents. The $project
stage in the aggregation pipeline allows us to include or exclude fields, create new fields, or even apply transformations to existing fields.
Here is an example of using $project
in the aggregation pipeline:
db.employee.aggregate([
{ $match: { joiningYear: 2018 } },
{ $project: { name: 1, department: 1, _id: 0 } }
])
Explanation:
- The
$match
stage filters the documents to only include employees who joined in 2018. - The
$project
stage reshapes the document to include only thename
anddepartment
fields, and excludes the_id
field (by setting_id: 0
)
Common Mistakes in Projection
Here are two common mistakes to avoid when using MongoDB projection:
1. Mixing Include and Exclude Fields
We cannot mix fields that are included (using 1
) and excluded (using 0
) in the same projection object. Doing so will result in an error. In this example, you are trying to include name
but exclude both _id
and salary
, which MongoDB does not allow in the same projection.
Incorrect Example:
db.employee.find({}, {name: 1, _id: 0, salary: 0}) // Invalid
Correct Example:
db.employee.find({}, {name: 1, _id: 0})
2. Not Excluding the _id
Field
By default, MongoDB includes the _id
field in all query results. If we want to exclude it, we must explicitly set _id: 0
in the projection.
Incorrect Example (still returns _id
):
db.employee.find({}, {name: 1, department: 1}) // Includes _id by default
Correct Example (excludes _id
):
db.employee.find({}, {name: 1, department: 1, _id: 0})
Conclusion
MongoDB projection is an essential feature for optimizing queries, especially in applications where large documents are involved. By selectively retrieving only the necessary fields, we can significantly reduce the load on our database and improve query performance. In this article, we explored various techniques for using projection with MongoDB, including the correct syntax, filtering, and examples. Additionally, we discussed the aggregation framework’s $project
stage, the limitations of certain operators, and common pitfalls to avoid. With this knowledge, we can now confidently use MongoDB projection to streamline our data retrieval processes