MongoDB Projection – How Projection in MongoDB Affects Performance

Job-ready Online Courses: Dive into Knowledge. Learn More!

In our last article, we have seen MongoDB Create & Drop Collection. In this article, we will learn introduction to MongoDB Projection. Moreover, we will also discuss how projection in MongoDB affects performance with examples.

So, let’s start the MongoDB Projection Tutorial.

What is MongoDB Projection?

MongoDB projection is a query where we can specify the fields we would like to have returned. We can do projection in MongoDB by adding a 0 or 1 next to fields name after including in a query. If you specify the parameter 1 it will be displayed and 0 will hide it.

Let’s understand it with an example of Projection in MongoDB.

i. Run a Query Without Projection in MongoDB

First, run a query without MongoDB projection to see the difference.

MongoDB Projection

Run a Query Without Projection in MongoDB

ii. Run a Query With Projection in MongoDB

We see that it shows all the fields and values without projection.

Run a Query With Projection in MongoDB

Run a Query With Projection in MongoDB

We see that only ObjectId and name comes in the result as we set 1 for name. ObjectId field is automatically included and can be excluded by setting a 0 for this field.

MongoDB Projection

A result of Projection in MongoDB – ObjectID

Although this is the exception for the _id field, you cannot mix 1 & 0. If you do, it will show some error saying “MongoDB Projection cannot have a mix of inclusion and exclusion”.

MongoDB Projection

MongoDB Projection – Error

This means you can either include fields or exclude them. You cannot do both at the same time.

Let’s exclude both the name & the city.

Excluding Name & City

Now include both the name & the city.

MongoDB Projection

Excluding Name & City


Hence, we have seen that how can we use MongoDB projection to query the document only for the specified fields. It helps us to find the data of our need easily. At last, we discuss how Projection in MongoDB affects query execution/Performance.

In the next article, we will learn the limiting and sorting of the records in MongoDB. Furthermore, if you have any query, feel free to ask in a comment section.

Your opinion matters
Please write your valuable feedback about DataFlair on Google


Leave a Reply

Your email address will not be published. Required fields are marked *