DZone
Database Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Database Zone > How To Create a MongoDB Projection?

How To Create a MongoDB Projection?

In this post, we will learn how to create a MongoDB Projection. Basically, projections allow us to retrieve selective fields of a document while querying a collection.

Saurabh Dashora user avatar by
Saurabh Dashora
CORE ·
Jan. 05, 22 · Database Zone · Tutorial
Like (3)
Save
Tweet
4.08K Views

Join the DZone community and get the full member experience.

Join For Free

In this post, we will learn how to create a MongoDB Projection. Basically, projections allow us to retrieve selective fields of a document while querying a collection.

If you are new to MongoDB, you can check out this detailed post about MongoDB CRUD Operations. This is because the CRUD operations form the basis for other complicated operations.

1 – What Is MongoDB Projection?

In MongoDB, we have collections. Collections comprise of documents. And within those documents, we have key/value pairs. Basically, you can think of the keys as fields of a document.

Projection helps find selective data from the documents. This is incredibly useful because we will usually have a huge number of records in a typical enterprise environment. If we process all these documents along with all the fields within them, it may create a huge load on network bandwidth. More often than not, we may be only interested in a subset of those fields for fulfilling some requirement. MongoDB projections are a great way to handle such a scenario.

Projections also use the find() function. See below syntax format.

db.<collection_name>.find({},{FIELD_NAME:BOOLEAN})

As you can see, this is exactly the same find() function syntax. The only addition is the boolean parameter for the field name. This parameter determines whether a particular field should be displayed or not.

2 – Writing MongoDB Projection

Let us imagine that we have some data in a Books collection as below:

{
    "_id" : ObjectId("61cd54a29f57d2539bb251fe"),
    "bookName" : "The Eye of the World",
    "authorName" : "Robert Jordan",
    "price" : "12"
}
{
    "_id" : ObjectId("61cd54b69f57d2539bb251ff"),
    "bookName" : "The Great Hunt",
    "authorName" : "Robert Jordan",
    "price" : "13"
}
{
    "_id" : ObjectId("61cd54c89f57d2539bb25200"),
    "bookName" : "The Dragon Reborn",
    "authorName" : "Robert Jordan",
    "price" : "11"
}


Now, if we wish to only fetch the bookName for all the documents, we can use a projection.

See the below example:

> db.books.find({}, {"bookName": 1}).pretty()
{
    "_id" : ObjectId("61cd54a29f57d2539bb251fe"),
    "bookName" : "The Eye of the World"
}
{
    "_id" : ObjectId("61cd54b69f57d2539bb251ff"),
    "bookName" : "The Great Hunt"
}
{
    "_id" : ObjectId("61cd54c89f57d2539bb25200"),
    "bookName" : "The Dragon Reborn"
}


As you can see, the output only contains the _id and the bookName field.

Basically, we pass a second argument which is also a JSON object. In the argument, we specify the field name and the boolean value for the same. Here, 1 means that we want the field to be in the projection. The default value of a field when we use projection is 0. Therefore, all other fields are automatically excluded from the projection.

3 – The _id Field

The _id field is a special field. Basically, this field is inserted by MongoDB for every document. It is also part of the projection by default. In other words, if we don’t specify anything, the _id field will be present in the output.

If we also want to hide the _id field, we need to pass boolean 0 for the same. See below example:

> db.books.find({}, {"_id": 0, "bookName": 1}).pretty()
{ "bookName" : "The Eye of the World" }
{ "bookName" : "The Great Hunt" }
{ "bookName" : "The Dragon Reborn" }


In the above snippet, we set the boolean for _id as false. The output only contains the bookName field.

Conclusion

With this, we have successfully learned how to create a MongoDB projection and how to include fields in a projection.

If you have any comments or queries about the post, please mention them in the comments section below.

MongoDB

Published at DZone with permission of Saurabh Dashora. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Application Scalability — How To Do Efficient Scaling
  • Top Six Kubernetes Best Practices for Fleet Management
  • The Right Way to Hybridize Your Product Development Technique
  • Maven Tutorial: Nice and Easy [Video]

Comments

Database Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo