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

Enterprise AI Trend Report: Gain insights on ethical AI, MLOps, generative AI, large language models, and much more.

2024 Cloud survey: Share your insights on microservices, containers, K8s, CI/CD, and DevOps (+ enter a $750 raffle!) for our Trend Reports.

PostgreSQL: Learn about the open-source RDBMS' advanced capabilities, core components, common commands and functions, and general DBA tasks.

AI Automation Essentials. Check out the latest Refcard on all things AI automation, including model training, data security, and more.

Related

  • A Developer's Guide to Database Sharding With MongoDB
  • CRUDing NoSQL Data With Quarkus, Part One: MongoDB
  • Achieving Inheritance in NoSQL Databases With Java Using Eclipse JNoSQL
  • Image Storage: Building a Node.js API With MongoDB

Trending

  • Building a Performant Application Using Netty Framework in Java
  • Architecture: Software Cost Estimation
  • Sprint Anti-Patterns
  • How To Optimize Your Agile Process With Project Management Software
  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
Like (3)
Save
Tweet
Share
4.8K 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

  • A Developer's Guide to Database Sharding With MongoDB
  • CRUDing NoSQL Data With Quarkus, Part One: MongoDB
  • Achieving Inheritance in NoSQL Databases With Java Using Eclipse JNoSQL
  • Image Storage: Building a Node.js API With MongoDB

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send 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: