DZone
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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Loading XML into MongoDB
  • Mastering Full-Stack Development: A Comprehensive Beginner’s Guide to the MERN Stack
  • How To Perform Data Migration in MongoDB Using Node.js
  • Leveraging AI and Vector Search in Azure Cosmos DB for MongoDB vCore

Trending

  • Simplify Authorization in Ruby on Rails With the Power of Pundit Gem
  • Power BI Embedded Analytics — Part 2: Power BI Embedded Overview
  • Integrating Security as Code: A Necessity for DevSecOps
  • Understanding and Mitigating IP Spoofing Attacks
  1. DZone
  2. Data Engineering
  3. Databases
  4. 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.

By 
Saurabh Dashora user avatar
Saurabh Dashora
DZone Core CORE ·
Jan. 05, 22 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
6.6K 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.

Related

  • Loading XML into MongoDB
  • Mastering Full-Stack Development: A Comprehensive Beginner’s Guide to the MERN Stack
  • How To Perform Data Migration in MongoDB Using Node.js
  • Leveraging AI and Vector Search in Azure Cosmos DB for MongoDB vCore

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!