MongoDB Projection Tutorial : Return Specific Fields From Query

MongoDB Projection helps to return the specific fields from the query (or you can say from the MongoDB collection). By default, when we query any collection in MongoDB, it returns all fields in matching documents. Now, at times, we may not want all the records from the collection but a few of them in the result set. So, in that case, we use MongoDB projection (using projection document) to limit the amount/fields of data.

In previous tutorial articles, you had already seen that how we query collection documents. We use MongoDB find command to query and fetch certain records from the collection matching the query.

Syntax is –

1

db.collection.find();

OR

1

db.collection.find().pretty();//This method returns the results in a better-organized way

For example, I have below collection ‘example’ with one record/document in this. Now, if I query the collection in mongo shell, it returns all documents or fields from the (matching) documents by default. See snapshot below –

1

2

3

4

5

6

7

>db.example.find().pretty();

{

"_id":ObjectId("5c8392793468f8dc38ad347e"),

"tutorial":"MongoDB",

"title":"MongoDB Projections Tutorial",

"Author":"Mohit Arora"

}

So, here you can see it has returned all the fields of the document from the collections.

But, what if we want to fetch only Tutorial or Title or Author from this document, how will we do? The answer is using MongoDB Projection. We will project specific fields to return from the query.

Before proceeding to MongoDB Projections, let’s recall how we fetch certain fields from SQL database.

Suppose, the collection ‘example’ is a table in SQL and Tutorial, Title, Author are its columns. Now, I want to fetch the only title from this table, how will I do? I will simply write below query which returns only title –

Oracle PL/SQL

1

selecttitlefromexample;-- instead of select * from example, which will return all the columns)

On executing this query, you will get title value i.e. MongoDB Projections Tutorial.

Now, I hope you have got a clear picture of what we are trying to achieve using Projections in MongoDB.

MongoDB Projection Example

Let’s see how we do projections in MongoDB. I will show you how we can fetch only title field from the collection in MongoDB using Projection (like how we saw earlier using SQL)

The syntax is –

1

db.collection_name.find({},{field_key:1or0})

** We need to set a list of fields with value 1 or 0. 1 is used to show the field while 0 is used to hide the fields.

1

2

3

4

5

>db.example.find({},{"title":1}).pretty();

{

"_id":ObjectId("5c8392793468f8dc38ad347e"),

"title":"MongoDB Projections Tutorial"

}

Now, there are two main things to consider here.

How we used find () method to use projection

_id field

Let’s understand these:

1) Find () method used projection document (as mentioned earlier) to project fields. The projection document is the second document in the find (). Hence, we have written as –

find ({},{“title”:1})

In the second document, we mentioned the field which we want to fetch. The syntactic way to do is – “fieldName”:1 //which means it will fetch Title attribute.

The question is what is this first document for. Basically, the first document is to filter the document for which we need the title attribute. Confused?

Now, we have two documents, one for Python and one for MongoDB. Assume, we want only the title for MongoDB tutorial.

This is how we do in SQL –

1

select title from example where tutorial='MongoDB';

Equivalent to this in MongoDB will be –

1

2

3

4

5

>db.example.find({"tutorial":"MongoDB"},{"title":1}).pretty();

{

"_id":ObjectId("5c8392793468f8dc38ad347e"),

"title":"MongoDB Projections Tutorial"

}

So, you can see 1the st document in find () method is used to filter the records from the collection (similar to having where clause in SQL).

I had a single document (only MongoDB and not Python) while demonstrating an example earlier, so I kept empty document there. But you can have filters in the 1st document along with projection fields in the 2nd document.

2) _id Field: Note that, _MongoDB prints _id field by default. If you do not want the _id field to be fetched, you will have to specifically tell MongoDB to not to return this field. This is how we do:

So, we can see projection helps in the inclusion of certain fields to be returned in the resultset.

Now, the good thing here is you can use projections for exclusion as well. For example, in case if we want the majority of the fields from the collection except a very few. For example, let me create new MongoDB collection named ‘demo’ having some more fields.

We want to return all the fields (tutorial, title, author, type from the demo collection except Course Duration field.

To achieve this, we have two options

Inclusion of all fields in the query (such as “tutorial”:1, “title”:1, “author”:1, “type”:1)

Exclusion of Certain fields i.e. return all but excluded fields. (This becomes helpful when we need only very few fields to be excluded from the result set. So, instead of writing “tutorial”:1, “title”:1, “author”:1, “type”:1 we can simply write “Course Duration”:0. and it will return in the matching result set and shows how we use projection to exclude)

Syntax:

1

db.demo.find({},{"Course Duration":0}).pretty();

Note:

** As mentioned earlier, MongoDB shows _id field by default. So, we can include/exclude them based on our need.

** Projection Field is case sensitive so use wisely (See carefully how I’ve written query)

MongoDB Projection in the Embedded Document

You can use projections in the embedded documents as well. Let’s say we have the following collection-

Here, if we want to project title field, we can set the query as –

1

db.TutorialsJar.find({},{"details.title":1,"_id":0}).pretty();

That’s all in this MongoDB Projection tutorial. In the upcoming article, we will learn about MongoDB Operators (Array Operators, Element Operators, Query Operator and Projection Operator etc. Do not forget to share it with your friends & colleagues. If you have any questions or feedback, do let us know in the comment section below.

Related

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

Comment

Name *

Email *

Website

All the data shown above will be stored by TutorialsJar on https://www.tutorialsjar.com/. At any point of time, you can contact us and select the data you wish to anonymize or delete so it cannot be linked to your email address any longer. When your data is anonymized or deleted, you will receive an email confirmation. We also use cookies and/or similar technologies to analyze customer behaviour, administer the website, track users' movements, and to collect information about users. This is done in order to personalize and enhance your experience with us.