For enquiries call:

Phone

+1-469-442-0620

April flash sale-mobile

HomeBlogWeb DevelopmentMongoDB Projection: Examples, Syntax, Operators and More

MongoDB Projection: Examples, Syntax, Operators and More

Published
24th Jan, 2024
Views
view count loader
Read it in
5 Mins
In this article
    MongoDB Projection: Examples, Syntax, Operators and More

    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.

    What is 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: 

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

    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 KnowledgeHut 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.knowledgeHutCollection.find().pretty() 

    What is MongoDB Projection?

    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. 

    How Does MongoDB Projection Works? 

    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: 

    Syntax 

    db.DATA_COLLECTION_NAME.find({}, {YOUR_FIELD_KEY: BOOLEAN}) 

    Let us break down this syntax to understand everything in detail. 

    • Here "DATA_COLLECTION_NAME" is the name of the table/Collection from where the records are to be retrieved for processing. 
    • YOUR_FIELD_KEY is the name of the column or data item that you want to process from the Collection 
    • BOOLEAN is the check to show or hide the Field value. 

    Let us take the example of knowledgeHutCollection 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.knowledgeHutCollection.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.knowledgeHutCollection.find( { status: "A" } ) 

    The result will look like the below item: 

    What is MongoDB Projection?

    To make it easier to understand this operation can be interpreted as the following SQL statement: 

    SELECT * from knowledgeHutCollection 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

    What is MongoDB Projection?

    Similarly, this operation can be interpreted as the following SQL statement: 

    SELECT item, status from knowledgeHutCollection WHERE status = "A" 

    MongoDB administration certification can help you further understand the Storage of data and other functionality related to MongoDB. 

    MongoDB Projection Operators 

    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: 

    • $elemMatch 
    • $slice 
    • $meta 

    Let us dive in to understand each one in depth: 

    1. $ Operator 

    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. 

    What is MongoDB Projection?

    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. 

    What is MongoDB Projection?

    Limitations of the $ operator: 

    • In a single MongoDB projection query, only a single $ operator can be used. 
    • It will only be applied to a single condition on the array field
    • The sort() function in the find() is applied before the $ operator and this function may cause the sort order to get distorted. 
    • The $ operator can only be utilized at the end of a field path. This restriction helps to mitigate any formatting issues. 

    2. $elemMatch 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. 

    What is MongoDB Projection?

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

    What is MongoDB Projection?

    Limitations of $elemMatch operator are as follows: 

    • The field to which the $elemMatch projection is applied is returned as the last field of the document, regardless of the order in which the fields are ordered. 
    • $elemMatch projection operator is not supported by find() operations on MongoDB views. 
    • The $elemMatch operator does not handle $text query expressions. 

    3. $slice Projection Operator

    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. 

    What is MongoDB Projection?

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

    What is MongoDB Projection?

    Limitations in $slice operator: 

    • In a nested array the $slice operator will only return the sliced element and will not return any other item, especially from MongoDB 4.4. 
    • The find() action is not supported by the $slice operator on MongoDB views. 
    • Due to a constraint imposed by MongoDB, the $slice operator cannot be combined with the $ projection operator. This is because top-level fields are not permitted to contain the $ symbol as part of the field name. 

    4. $meta Operator with Examples 

    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: 

    • "textScore" Keyword. This keyword effectively finds how precisely a search term is related with the given field in a document. The "textScore" yields the score associated with the provided $text.
    • "indexKey" Keyword. Introduced in MongoDB 4.4 as a preferred alternative to the cursor.returnKey() function. For a document that uses a non-text index, this function returns the index key. A key thing to note is that this keyword should not be used in production situations; it should only be used for debugging purposes. 

    Now, let's look at a few $meta Operator MongoDB projection examples : 

    For {$meta: "textScore"}, we will be using the articles collection like below: 

    What is MongoDB Projection?

    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" } } 
    ) 

    What is MongoDB Projection?

    Usage and Limitations of $meta operator in projection: 

    • The {$meta: "$textScore"} expression is used in a projection query to obtain the text score. The expression can be set up as an inclusion or exclusion in the projection statement. The limitation that it comes with is that if the expression is set to an existing field the projected metadata value will get overwritten by the current value in the field. 
    • The $meta expression when paired with sort() function will also sort the "textScore" metadata in descending order. 
    • Both the projection and the sort procedures can use a different field name for the expression when $meta: "$textScore" is used. The query system will ignore the sort's field name (). 

    Projection Queries with Examples 

    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.

    1. Return Only Specified Fields 

    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. 

    2. Return all Except Excluded Fields 

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

    3. Return Specified Fields in an Embedded Document 

    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: 

    • The _id field (returned by default), 
    • The item field, 
    • The uom field in the size document. 
    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 } }. 

    4. Return Specified Fields in an Embedded Document in an Array 

    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 _id field (default Value), 
    • The item field, 
    • The qty field, that is let’s say embedded in the instock array. 

    The query for the same on inventory collection will be as below: 

    db.inventory.find( { status: "A" }, { item: 1, "instock.qty": 1 } ) 

    Conclusion 

    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. KnowledgeHut’s MongoDB professional certification covers MongoDB Projection in depth.

    Looking to become a Python developer? Discover the best Python developer course near you and unlock endless possibilities in the world of coding. Start your journey today!

    Frequently Asked Questions (FAQs)

    1Does MongoDB projection improve performance?

    Yes, Projections help to limit fields returning from query results, which can improve performance due to the following reasons:

    1. Removing unneeded fields from query results helps in saving on network bandwidth.
    2. It limits the result fields to achieve a covered query, therefore, returning indexed query results without fetching full documents.
    2How is the projection used in MongoDB compass?

    To set a projection in MongoDB Compass use the below steps

    1. In the Query Bar, click Options.
    2. Enter the projection document into the Project field. To include fields:
    3. Click Find to run the query and view the updated results. For query result sets larger than 1000 documents, Compass shows a sampling of the results. 

    3How do I project an array in MongoDB?

    For fields containing arrays, MongoDB provides the following projection operators for manipulating arrays: $elemMatch, $slice, and $. $elemMatch, $slice, and $ are the only way for project-specific elements included in the returned array.


    4How do I find specific data in MongoDB?

    There are functions and queries that we can use to find specific data in MongoDB Documents, notables to mention are Find() and FindOne(), Also, projections can be used to find specific data in the Document.

    Profile

    Abhresh Sugandhi

    Author

    Abhresh is specialized as a corporate trainer, He has a decade of experience in technical training blended with virtual webinars and instructor-led session created courses, tutorials, and articles for organizations. He is also the founder of Nikasio.com, which offers multiple services in technical training, project consulting, content development, etc.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon