Mongodb Projection & Projection Operators Explained

Mongodb Projection & Projection Operators Explained

In MongoDB, we use the find() method to retrieve data. However, find() retrieves all the fields in a document without any filtering.

MongoDB projection solves this problem by enabling the find() function to be used with data filtering arguments, which allow users to extract only the necessary data fields from a document.

In this hands-on article, we’ll show you:

(This article is part of our MongoDB Guide. Use the right-hand menu to navigate.)

How MongoDB projection works

MongoDB projection is a powerful tool that can be used to extract only the fields you need from a document—not all fields. It enables you to:

  • Project concise and transparent data
  • Filter the data set without impacting the overall database performance

Because MongoDB projection is built on top of the existing find() method, you can use any projection query without significant modifications to the existing functions. Plus, projection is a key factor when finding user-specific data from a given data set.

Basic Syntax of MongoDB Projection

db.collection_name.find({},{<field> : <value>})

MongoDB projection uses the same find syntax, but we also add a set of parameters to the find function. This set of parameters informs the MongoDB instance of which fields to be returned.

Consider the following collection called “vehicleinformation”

We will try to retrieve the model year of the vehicle make Toyota (make: ‘Toyota’)

Normal find() statement

db.vehicleinformation.find({make : "Toyota"}).pretty()

Result:

In this statement, we receive all the data within the document where make is Toyota. To get only the year, we can use projection, as shown below.

MongoDB projection statement

db.vehicleinformation.find({make : "Toyota"}, {year : 1}).pretty()

Result:

In the projection statement, we use the year field with the Boolean value 1 (True) to indicate that we only require the “year” field. The limitation is that MongoDB will return the object ID (_id) of each document unless we explicitly specify that we do not require the object ID.

MongoDB projection statement with “_id” excluded

db.vehicleinformation.find({make : "Toyota"}, {year : 1, _id : 0}).pretty()

Result:

In this statement, we pass 0 as the Boolean operator to indicate that we do not require the object ID field.

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.