MongoDB Projection – How Projection in MongoDB Affects Performance


1. Objective

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.

MongoDB Projection

MongoDB Projection – How Projection in MongoDB affects Query

2. 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 Learn How MongoDB Create Database

Let’s understand it with MongoDB Projection example.

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.

MongoDB Projection

Run a Query With Projection in MongoDB

Let’s Explore Advantages and Disadvantages of 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.

Read about Features of MongoDB in detail

Let’s exclude both the name & the city.

MongoDB Projection

Excluding Name & City

Now include both the name & the city.

MongoDB Projection

Excluding Name & City

3. Conclusion

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.

For reference