MongoDB Projection

MongoDB provides more features to its users for extracting data from the Mongo database. In this article, you will learn about the MongoDB projection queries.

In MongoDB, projection implies choosing only the necessary data instead of choosing entire of the data of a document. If a document has 7 fields and you need to show just 3, then select only 3 fields from them. It is a particular type of query where we can specify fields that we want to get in the output.

In MongoDB, projection means selecting only the necessary data rather than selecting all document fields.

Syntax of Projections

The projection can be done by using the db.collection.find() method, where you need to mention the field that needs to be explicitly returned. This can be possible by expressly consolidating the field names in your query, and adding a 1 or 0 with them for determining whether this needs to be returned or not.

db.collection.find({}, {KEY:1 or 0});

Here, the KEY is the field and we can set its value either 1 or 0. If we want to hide the field from result data, then set it to 0 and if we want to show the data, set it to 1. By this, we can control on the find() method and fetch only the required data.

Example of MongoDB Projection

Suppose we have the following 'students' collection.

{ "_id" : ObjectId("5b7ddc4f529cbc23546dc4c7"), "name" : "Jorz Rai", "age" : 10, "class" : "5A" }
{ "_id" : ObjectId("5b7ddf10529cbc23546dc4c8"), "name" : "Rana Soi", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4c9"), "name" : "Andy Joya", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4ca"), "name" : "Mary Soi", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4cb"), "name" : "Priska Somya", "age" : 12, "class" : "6A" }
mongodb sort

If we need to hide the 'age' field, run the following query -

db.students.find({}, {age:0});
Output of the above code:
{ "_id" : ObjectId("5b7ddc4f529cbc23546dc4c7"), "name" : "Jorz Rai", "class" : "5A" }
{ "_id" : ObjectId("5b7ddf10529cbc23546dc4c8"), "name" : "Rana Soi", "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4c9"), "name" : "Andy Joya", "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4ca"), "name" : "Mary Soi", "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4cb"), "name" : "Priska Somya", "class" : "6A" }
mongodb skip





Read more articles


General Knowledge



Learn Popular Language