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.
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 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.
ii. Run a Query With Projection in MongoDB
We see that it shows all the fields and values without projection.
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.
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”.
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.
Now include both the name & the 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.