Projection in MongoDB [With Examples]

MongoDB is one of the most famous modern-day databases to handle and manage big data. It is a NoSQL document-oriented database that uses JSON like documents to make it easier for managing data.

Various MongoDB project ideas can be easily brought to life. However, MongoDB has a few drawbacks as well. By default, any query for a specific document will show all the data- this issue is solved with the help of MongoDB projection.

What is Projection in MongoDB?

Projection in MongoDB limits the output of data to specified fields instead of showing all of them. This is done with the help of the find() method. The find() method accepts an optional parameter that allows us to either include or exclude certain output fields. Let’s delve deep into how to use projection in MongoDB.

Syntax of the Find() Method

Projection in MongoDB is made with the help of the find() method, the syntax for which is:

db.collection_name.find({}, {field_Key:1 or 0})

In the above syntax, collection_name is the document from which we need to retrieve data. Then there are two parameters in the find() method- the first accepts a query, and the second is used for projection. The field_Key in the syntax is the name of the field that we want to include or exclude.

We need to pass a boolean value for each field_Key. This value defines whether we want to include the field or exclude it. If we input 1 against a field, it will be shown in the results, and if we include 0, it will be hidden.

The example database

Let’s create an example document in a database so that we can refer to it throughout this article.

db.example.studentData([

{_id: ObjectId(“59kf63795bc1d”), student_name: “Alexander”, student_id: 01, student_status: “A”, student_age: 22}

{_id: ObjectId(“59ke62794bc1d”), student_name: “Steve”, student_id: 02, student_status: “A”, student_age: 23}

{_id: ObjectId(“59kg73795bf1e”), student_name: “Luke”, student_id: 03, student_status: “A”, student_age: 21}

{_id: ObjectId(“59kb69995ah1d”), student_name: “Bravo”, student_id: 04, student_status: “B”, student_age: 25}

])

This is our database document named example that we will use as a reference in all our examples.

Retrieving data with and without projection in MongoDB

1. The syntax for retrieving without projection

Retrieving all the fields (as not using projection) of students with student_status: “A.”

db.example.find({student_status: “A”})

This corresponds to Select * from example WHERE student_status = “A” query in SQL. Retrieving data without projection in MongoDB will produce the following result:

{“_id”: ObjectId(“59kf63795bc1d”), “student_name”: “Alexander”, “student_id”: 01, “student_status”: “A”, student_age: 22}

{“_id”: ObjectId(“59ke62794bc1d”), “student_name”: “Steve”, “student_id”: 02, “student_status”: “A”, “student_age”: 23}

{“_id”: ObjectId(“59kg73795bf1e”), “student_name”: “Luke”, “student_id”: 03, “student_status”: “A”, student_age: 21}

By default, it displays all the fields of the data where student_status = “A.” To limit the output fields we can use projection in MongoDB.

2. The syntax for retrieving with projection

Retrieving student_name and student_status of all the students.

db.example.find({}, {student_name: 1, student_status: 1})

This will show the following result:

{“_id”: ObjectId(“59kf63795bc1d”), “student_name”: “Alexander”, “student_status”: “A”}

{“_id”: ObjectId(“59ke62794bc1d”), “student_name”: “Steve”, “student_status”: “A”}

{“_id”: ObjectId(“59kg73795bf1e”), “student_name”: “Luke”, “student_status”: “A”}

{“_id”: ObjectId(“59kb69995ah1d”), student_name: “Bravo”, student_status: “B”}

The _id is shown by default while using projection in MongoDB unless we suppress it.

Suppressing _id while using projection in MongoDB

Suppressing the default _id and showing student_id, student_name, and student_status of all the students.

db.example.find({}, {_id: 0, student_id: 1, student_name: 1, student_status: 1})

This will produce the following result:

{“student_id”: 01, “student_name”: “Alexander”, “student_status”: “A”}

{“student_id”: 02, “student_name”: “Steve”, “student_status”: “A”}

{“student_id”: 03, “student_name”: “Luke”, “student_status”: “A”}

{“student_id”: 04, “student_name”: “Bravo”, student_status: “B”}

3. Combining Inclusion and Exclusion

Excluding _id and student_id, including student_name and student_status of all the students.

db.example.find({}, {_id: 0, student_id: 0, student_name: 1, student_status: 1})

This will produce the following result:

Error: error: {

“waitedMS” : NumberLong(0),

“ok” : 0,

“errmsg” : “Projection cannot have a mix of inclusion and exclusion.”,

“code” : 2

}

Combining inclusion and exclusion while using MongoDB projection will throw an error because we cannot perform both in the same query. The _id field is an exception to this rule.

You would have noticed that we had used a combination of inclusion and exclusion in our previous example where we suppressed _id and showed some other fields, and it worked fine. Because of the exception to the rule, we had excluded _id and included the rest of the fields.

4. Specifying Projection in MongoDB by Exclusion

Excluding _id and student_status of all the students and showing the other fields.

db.example.find({}, {_id: 0, student_status: 0})

{“student_name”: “Alexander”, “student_id”: 01, “student_age”: 22}

{“student_name”: “Steve”, “student_id”: 02, “student_age”: 23}

{“student_name”: “Luke”, “student_id”: 03, “student_age”: 21}

{“student_name”: “Bravo”, “student_id”: 04, “student_age”: 25}

You can also use the four projection operators to limit the output fields, but they are not supported by the find() method. The projection operators that can be used are- $, $elemMatch, $slice, and $meta.

Also Read: MongoDB Real World Use Cases

Conclusion

With the use of projection in MongoDB, we can take control of showing data in the front end, which increases its real-world use cases. MongoDB has achieved several milestones in recent years. This has made the future scope of MongoDB bright, and numerous businesses are looking for full-stack developers with the knowledge of MongoDB.

Now is, therefore, a great time to include the skills of MongoDB to your resume. But then, only managing a database is not enough in today’s competitive world. Hence, it would help if you aimed to become a full-stack developer or learn business analytics to understand and analyze the data you are managing and help businesses perform well. upGrad can help you get started.

We at upGrad provide detailed learning sources along with hands-on experience and job assistance. We have collaborated with multiple institutes to get you the best of education and certification. You can choose whether you want to opt-in for the Business Analytics certification course or go for a Full-stack software development PG Diploma course. Whatever you want to pursue as a career in your life, we have got you covered.

Lead the Data Driven Technological Revolution

400+ HOURS OF LEARNING. 14 LANGUAGES & TOOLS. IIIT-B ALUMNI STATUS.
Enroll Today

Leave a comment

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

×
Aspire to be a Data Scientist
Download syllabus & join our Data Science Program and develop practical knowledge & skills.
Download syllabus
By clicking Download syllabus, I authorize upGrad and its representatives to contact me
via SMS / Email / Phone / WhatsApp / any other modes.
I agree to upGrad terms and conditions and our privacy policy.