MongoDB Projection

In this post, we will see how to get the selected fields of the documents rather than all fields using MongoDB projection.
In MongoDB, projection means selecting only the necessary data rather than selecting a whole of the data of a document. If a document has 5 fields and you need to show only 3, then select only 3 fields from them.

The find() Method

In MongoDB's find() method, the second optional parameter is a list of fields that you want to retrieve. In MongoDB, when you execute find() method, then it displays all fields of a document. To limit this, you 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.

Syntax

The basic syntax of find() method with projection is as follows −
> db.COLLECTION_NAME.find({},{KEY:1})

Example

Consider the collection posts has the following data −
> db.posts.find().pretty();
{
        "_id" : ObjectId("5e184a067695f4d696a0598d"),
        "title" : "MongoDB Overview",
        "description" : "MongoDB is no sql database",
        "by" : "Java Guides",
        "url" : "https://javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100
}
{
        "_id" : ObjectId("5e184a067695f4d696a0598e"),
        "title" : "NoSQL Database",
        "description" : "NoSQL database doesn't have tables",
        "by" : "Java Guides",
        "url" : "https://javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 20,
        "comments" : [
                {
                        "user" : "user1",
                        "message" : "My first comment",
                        "dateCreated" : ISODate("2013-12-10T09:35:00Z"),
                        "like" : 0
                }
        ]
}
The following example will display the title and description of the document while querying the document.
> db.posts.find({},{"title":1,description:1}).pretty();
{
        "_id" : ObjectId("5e184a067695f4d696a0598d"),
        "title" : "MongoDB Overview",
        "description" : "MongoDB is no sql database"
}
{
        "_id" : ObjectId("5e184a067695f4d696a0598e"),
        "title" : "NoSQL Database",
        "description" : "NoSQL database doesn't have tables"
}
If you want to retrieve the only title of the posts then use the following query:
> db.posts.find({},{"title":1}).pretty();
{
        "_id" : ObjectId("5e184a067695f4d696a0598d"),
        "title" : "MongoDB Overview"
}
{ "_id" : ObjectId("5e184a067695f4d696a0598e"), "title" : "NoSQL Database" }
Note: In MongoDB, when you execute find() method, then it displays all fields of a document. To limit this, you 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.

Summary

The below diagram shows the summary of all the commands used in this post:



Comments