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 –

db.collection.find();

OR

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 –

MongoDB Projection Examples

> 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 –

select title from example; -- 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 –

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

** 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.

MongoDB Projecting Fields

> 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?

Let me add one more document in this collection. We have now following documents in the collection:

Inserting New Documents in Collection

>db.example.insert({tutorial: "Python",title: "Python Tutorial", Author: "Mohit Arora"})
WriteResult({ "nInserted" : 1 })
> db.example.find().pretty();
{  
   "_id" : ObjectId("5c8392793468f8dc38ad347e"), 
   "tutorial" : "MongoDB", 
   "title" : "MongoDB Projections Tutorial", 
   "Author" : "Mohit Arora"
}
{       
    "_id" : ObjectId("5c8395a2f57d03692bcdccb6"), 
    "tutorial" : "Python",   
    "title" : "Python Tutorial", 
    "Author" : "Mohit Arora"
}
>

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 –

select title from example where tutorial='MongoDB';

Equivalent to this in MongoDB will be –

MongoDB Projection On Filter

> 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:

We use “_id”:0 along with project fields in the projection document.

MongoDB Projection with Filter id field

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

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.

Sample MongoDB Collection

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)

Syntax:

db.demo.find({},{"tutorial":1,"title":1,"Author":1,"Type":1}).pretty();

MongoDB Inclusion Projection Examples

  • 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:

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

MongoDB Exclusion Projection Examples

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-

MongoDB Projections in Embedded Document

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

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

Projections in Embedded Document

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.

Mohit Arora
Follow me