Projection in MongoDB [With Examples]
Updated on Nov 23, 2022 | 5 min read | 11.5k views
Share:
For working professionals
For fresh graduates
More
Updated on Nov 23, 2022 | 5 min read | 11.5k views
Share:
Table of Contents
Mongo DB is a popular NoSQL and open-source document-oriented database which allows a highly scalable and flexible document structure. In my view, its speed, attributed to efficient storage and indexing techniques, surpasses that of traditional RDBMS. As a NoSQL solution, MongoDB is specifically designed to adeptly handle substantial volumes of data. To get the most out of MongoDB, take a close look at its features and capabilities. Understanding why it's widely used will help you make the most of this tool. Please check out MongoDB professional certification.
Though when you want to fetch selective information from a huge number of records, MongoDB will process a whole lot of unnecessary data and at the same time put lots of pressure on the overall database performance. To overcome such issues, MongoDB provides a special feature known as MongoDB Projection.
MongoDB Projection is a special feature allowing you to select only the necessary data rather than selecting the whole set of data from the document. For Example, If a Document contains 10 fields and only 5 fields are to be shown the same can be achieved using the Projections.
This enable us to:
Let us check out an example to understand better how projections work:
Firstly, get familiar with how MongoDB stores data, as MongoDB is schemaless it stores data in separate documents, here table is denoted as "Collection", a row is "Document" and the column means "Field".
Consider the following collection for a MongoDB projection example, where we have a data set of upGrad inventory with some documents and fields associated with them.
When we use the find command, we fetch all the data set from the collection as follows.
db.upGradCollection.find().pretty()
Here we are fetching all the data that our DB has with no filters. Later in the article, we will work on the same data set to perform MongoDB Projections, but for now, let us first understand how Projections work.
MongoDB projections are constructed on top of the existing find() query and therefore making it easier to use without significant modifications to the existing functions/queries. Moreover, projection plays a key factor when looking for user-centric data from a given large data set.
A sample Syntax that you can use to retrieve the limited amount of data using Projection in MongoDB can be written as follows:
db.DATA_COLLECTION_NAME.find({}, {YOUR_FIELD_KEY: BOOLEAN})
Let us break down this syntax to understand everything in detail.
Let us take the example of upGradCollection that we discussed above to understand the depth of projection by processing some data.
We already wrote a query for the MongoDB projection example that will retrieve all the available records in the selected collection in a readable format with the help of pretty(), the same can be found again below.
db.upGradCollection.find().pretty()
Now we will use Projection on this document to specify or restrict fields to return. If want to return all fields from all documents in the inventory collection where the status equals "A", the query will look like the one below:
db.upGradCollection.find( { status: "A" } )
The result will look like the below item:
To make it easier to understand this operation can be interpreted as the following SQL statement:
SELECT * from upGradCollection WHERE status = "A"
Though there is more that we can do with projections, let's suppose we want to get only some associated fields from the document, A projection can also explicitly enclose several fields by setting the <field> to 1 in the projection document.
db.inventory.find( { status: "A" }, { item: 1, status: 1, _id: 0 } )
In the result set for the above query, only the item and status fields are returned in the matching documents whereas the _id field is Suppressed
Similarly, this operation can be interpreted as the following SQL statement:
SELECT item, status from upGradCollection WHERE status = "A"
MongoDB administration certification can help you further understand the Storage of data and other functionality related to MongoDB.
MongoDB projection method positively impacts database performance as it reduces the workload of the find query when trying to retrieve specific data from a document, minimizing resource usage.
To enhance the querying and reduce the workload, multiple operators can be used within a projection query like the ones below:
Let us dive in to understand each one in depth:
The $ operator is utilized in scenarios where there is a need to limit an array to project only the first element that matches the condition of the query, if no query condition is present, the first element is returned in the specified MongoDB projection array, and a sample syntax of the same can be seen below:
db.collection.find( { <array>: <condition> ... }, { "<array>.$": 1 } )
Example:
Let us check out the "students" Collection this time to understand the functioning of the $ operator.
db.students.find( { semester: 1, grades: { $gte: 85 } }, { "grades.$": 1 } )
Using the $ operator will only return the MongoDB projection first element of array where it is equal to or greater than 85.
Limitations of the $ operator:
Similar to the $ operator, the $elemMatch operator also limits the contents of an array to the first element that fits the given constraint. Though, there is a minor difference from the $ operator because the $elemMatch projection operator needs an explicit condition argument.
Syntax as follows:
db.collection.find( { <array>: <condition> ... }, { "<array>.$elemMatch": ($elemMatch operator) } )
Example:
Below you can check the "schoolsdData" collection that we will use to demonstrate the $elemMatch operator.
We need to write an operation that returns the following documents that have a zipcode equal to `63109` and projects the students array using $elemMatch:
db.schools.find( { zipcode: "63109" }, { students: { $elemMatch: { school: 102 } } } )
Limitations of $elemMatch operator are as follows:
The $slice operator bounds the number of elements that should be returned as the output of a MongoDB projection query.
Syntax:
db.collection.find( <query>, { <array Field>: { $slice: <number> } })
Now we'll use the "postsData" collection to demonstrate the $slice operator.
We want to get data from the comments array to return the array with its first three elements. If the array contains less than three elements, all elements of the array are returned.
db.posts.find( {}, { comments: { $slice: 3 } } )
Limitations in $slice operator:
The $meta operator gives us the capability to extract the metadata associated with a document. Both MongoDB projection and Aggregation support the $meta operator, though for now let us just dive into Projections.
The $meta operator uses the following syntax.
{ $meta: <metaDataKeyword> }
The "metaDataKeyword", represents these values:
Now, let's look at a few $meta Operator MongoDB projection examples :
For {$meta: "textScore"}, we will be using the articles collection like below:
We first add an index to the Document and then we use the textScore meta operator to include the score assigned to each matching document.
db.articles.createIndex( { title: "text"} )
db.articles.find(
{ $text: { $search: "cake" } },
{ score: { $meta: "textScore" } }
)
Usage and Limitations of $meta operator in projection:
Let us look at some example projection queries in this section.
Not specifying fields in a query is similar to SELECT * in SQL. If you are looking only to return a subset of fields, you'd specify them in the SELECT clause like below:
SELECT Id, name, is_active FROM customers
This is similar to returning all fields in matching Documents just like one of the above queries
db.inventory.find( { status: "A"} )
Let us check out some other examples to understand the variations in queries.
In case you need to return only the specified fields from a document, several fields can be included in a projection by setting the <field> to 1 in the projection document.
A good MongoDB projection example could be the below Query
db.inventory.find( { status: "A" }, { item: 1, status: 1 } )
The result set associated with this query will contain only the item, status, and, the _id (by default) fields in the matching documents.
Similarly, when you want to remove or suppress the fields returning in the matching document, projections can be used to exclude specific fields. The following example will yield all fields except for the status and the instock fields in the corresponding documents:
db.inventory.find( { status: "A" }, { status: 0, instock: 0 } )
In an embedded document, certain fields can be returned as per the need of the result set. To do so set the embedded field in the projection document to 1 and use the dot notation to refer to it.
The following example returns:
db.inventory.find(
{ status: "A" },
{ item: 1, "size.uom": 1 }
)
Starting in MongoDB 4.4, you can also specify embedded fields using the nested form, e.g. { item: 1, status: 1, size: { uom: 1 } }.
To return specific fields in an array format you can use dot notation to grab the project-specific fields from inside documents embedded in an array.
Let us take this example that specifies a projection to return:
The query for the same on inventory collection will be as below:
db.inventory.find( { status: "A" }, { item: 1, "instock.qty": 1 } )
I see projections in MongoDB as similar to choosing specific columns in SQL. Even though it may seem a bit odd to use them for fetching less data, as the database grows, using projections allows us to control what I retrieve with each read or write. This can enhance efficiency and overall performance.
I hope this article clears up the concept of projections in MongoDB and how to use them to create efficient MongoDB queries. UpGrad's MongoDB tutorial covers MongoDB Projection in depth.
Embark on a journey into Software Engineering with our sought-after courses—practical projects, expert mentorship, and job-ready skills!
Begin your journey into Software Development with our popular free courses—gain hands-on experience, receive expert guidance, and develop the skills needed to jumpstart your career!
Embark on your journey into Software Development with our sought-after courses—gain practical experience through hands-on projects, receive expert mentorship, and develop the skills employers are looking for!
Begin your journey into Software Development with our collection of popular articles—offering practical knowledge, expert insights, and essential skills to boost your career prospects!
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources