Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconBig Databreadcumb forward arrow iconProjection in MongoDB [With Examples]

Projection in MongoDB [With Examples]

Last updated:
15th Sep, 2020
Views
Read Time
6 Mins
share image icon
In this article
Chevron in toc
View All
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:

Ads of upGrad blog

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.

Explore our Popular Software Engineering Courses

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.

Explore Our Software Development Free Courses

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”}

In-Demand Software Development Skills

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.

Read our Popular Articles related to Software Development

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.

Ads of upGrad blog

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.

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Profile

Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.
Get Free Consultation

Select Coursecaret down icon
Selectcaret down icon
By clicking 'Submit' you Agree to  
UpGrad's Terms & Conditions

Our Popular Big Data Course

Frequently Asked Questions (FAQs)

1Between MongoDB and RDBMS, which one is preferred more and why?

The differences between MongoDB and RDBMS are many in various aspects. MongoDB is a NoSQL database that is document-oriented. It stores data in the form of a Binary JavaScript Object Notation, which is further stored in a collection. RDMS, on the other hand, is a relational database management system. MongoDB is scalable, horizontally and vertically, but RDBMS is only vertically scalable. MongoDB isn’t equipped enough to work with difficult joins whereas RDBMS is supportive of complex joins. Another big difference is with the processors. As the number of processors increases in MongoDB, the performance enhances. However, in RDBMS, the performance is based entirely on the RAM capacity.

2MongoDB is a NoSQL database but does it support SQL?

There are no direct means that MongoDB can implement to get support from SQL. However, MongoDB uses its very own query language. MongoDB’s crud operations are performed using MongoDB’s query language. Furthermore, MongoDB Connector for BI can be used to work with MongoDB tables and collections. With these techniques, you can implement MongoDB to work with SQL.

3Since MongoDB uses BSON, what is the difference between JSON and BSON?

JSON stands for JavaScript Object Notation which is similar to XML. JSON is a human-readable format that is mainly used for data exchange and is considered the standard format of all kinds. JSON is presently the most standard means of data exchange on the world wide web. It is also used avidly in Rest APIs. Booleans, numbers, arrays, and strings are the supported JSON formats. BSON is a binary encoding, which stands for Binary JavaScript Object Notation that is used by MongoDB for storing documents. Its characteristics and usage are similar to JSON. It also makes room to accommodate data types like Date. BSON documents are generally ordered. In terms of space, BSON works with less space compared to JSON which makes it fast. Encoding and decoding in BSON are very swift.

Explore Free Courses

Suggested Blogs

Top 10 Hadoop Commands [With Usages]
11944
In this era, with huge chunks of data, it becomes essential to deal with them. The data springing from organizations with growing customers is way lar
Read More

by Rohit Sharma

12 Apr 2024

Characteristics of Big Data: Types & 5V’s
5740
Introduction The world around is changing rapidly, we live a data-driven age now. Data is everywhere, from your social media comments, posts, and lik
Read More

by Rohit Sharma

04 Mar 2024

50 Must Know Big Data Interview Questions and Answers 2024: For Freshers & Experienced
7304
Introduction The demand for potential candidates is increasing rapidly in the big data technologies field. There are plenty of opportunities in this
Read More

by Mohit Soni

What is Big Data – Characteristics, Types, Benefits & Examples
185807
Lately the term ‘Big Data’ has been under the limelight, but not many people know what is big data. Businesses, governmental institutions, HCPs (Healt
Read More

by Abhinav Rai

18 Feb 2024

Cassandra vs MongoDB: Difference Between Cassandra & MongoDB [2023]
5468
Introduction Cassandra and MongoDB are among the most famous NoSQL databases used by large to small enterprises and can be relied upon for scalabilit
Read More

by Rohit Sharma

31 Jan 2024

13 Ultimate Big Data Project Ideas & Topics for Beginners [2024]
100324
Big Data Project Ideas Big Data is an exciting subject. It helps you find patterns and results you wouldn’t have noticed otherwise. This skill
Read More

by upGrad

16 Jan 2024

Be A Big Data Analyst – Skills, Salary & Job Description
899709
In an era dominated by Big Data, one cannot imagine that the skill set and expertise of traditional Data Analysts are enough to handle the complexitie
Read More

by upGrad

16 Dec 2023

12 Exciting Hadoop Project Ideas & Topics For Beginners [2024]
20845
Hadoop Project Ideas & Topics Today, big data technologies power diverse sectors, from banking and finance, IT and telecommunication, to manufact
Read More

by Rohit Sharma

29 Nov 2023

Top 10 Exciting Data Engineering Projects & Ideas For Beginners [2024]
40145
Data engineering is an exciting and rapidly growing field that focuses on building, maintaining, and improving the systems that collect, store, proces
Read More

by Rohit Sharma

21 Sep 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon