Table of contents
1.
Introduction
2.
What are Projections?
3.
How Does MongoDB Projection Work?
4.
Basic Projections
4.1.
Create a Collection named “students”
4.2.
Retrieve Names from Collection
4.3.
Retrieve Ages and Emails from Collection
4.4.
Excluding email Fields from Collection
4.5.
Nested Documents
4.6.
Retrieve Names from Nested Documents
5.
Operators in MongoDB Projection
5.1.
1. $
5.1.1.
Limitation:
5.2.
2. $elemMatch
5.2.1.
Limitation:
5.3.
3. $slice
5.3.1.
Limitation:
5.4.
4. $meta
5.4.1.
Limitation:
6.
Frequently Asked Questions
6.1.
How do I insert data into MongoDB?
6.2.
How does MongoDB differ from traditional relational databases?
6.3.
How do I connect to MongoDB?
7.
Conclusion
Last Updated: Feb 5, 2025
Medium

MongoDB Projections

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

MongoDB, a scalable NoSQL database, excels at data retrieval using projections. Projections enable accurate selection of document fields, reducing data transfer and enhancing query efficiency by fetching only the necessary data, an important feature in MongoDB's popularity.

In this article, we will learn the MongoDB Projections, concept of projections, and code examples and their corresponding output.

MongoDB Projections

What are Projections?

Projections, in Mongodb, are similar to selecting parts of a picture rather than the entire thing. Think of it as having a book and only wanting to read paragraphs without being concerned about the rest. Projections work in a way when dealing with data.

In MongoDB, data is stored in documents like pages in a book. Each document contains pieces of information such as a person's name, age, and email address. Projections allow you to choose which parts of the document you want to view, like selecting which paragraphs to read.

For example, if you have a list of people with their names, ages, and emails but are only interested in their names, you can use projections to specify, "Please provide me with the names." This helps improve query performance by avoiding data retrieval.

Projections in MongoDB assist in focusing on data within documents, making it simpler to retrieve only what is needed than the entire document. It's akin to looking at a paragraph of the entire page in a book, saving time and resources when working with data.

How Does MongoDB Projection Work?

Basic Projections

Basic projections in MongoDB allow you to specify which fields you want to include or exclude when querying documents from a collection. Here are examples of basic projections:

Create a Collection named “students”

db.students.insertMany([
  {
  "_id": 1,
  "name": "aditya",
  "age": 19,
  "email": "aditya@rv.com"
},
  {
  "_id": 2,
  "name": "Shubham",
  "age": 20,
  "email": "Shubham@rv.com"
},
{
  "_id": 3,
  "name": "Hritik",
  "age": 21,
  "email": "Hritik@rv.com"
}
]);

Retrieve Names from Collection

To retrieve only the names of all of the students in the collection.

db.students.find({}, { _id: 0, name: 1 });

Output:

Output1

Retrieve Ages and Emails from Collection

To retrieve only the ages and emails of all the students.

db.people.find({}, { _id: 0, age: 1, email: 1 });

Output:

Output2

Excluding email Fields from Collection

In some cases, we should retrieve all fields except for some. To exclude individual fields, we can use 0 inside the projection.

To retrieve all fields except the email addresses of all of the students in the collection.

db.students.find({}, { email: 0 });

Output:

Output3

Nested Documents

MongoDB allows you to have nested documents. We have a collection of series with the following structure:

{
  "_id": 1,
  "title": "Money Heist",
  "actor": {
"name": "Professor",
"age": 40
  }
}

Retrieve Names from Nested Documents

To retrieve only the author's name

db.series.find({}, { _id: 0, "actor.name": 1 };

Output

Output4

Operators in MongoDB Projection

1. $

In programming, the dollar sign ($) is commonly used as a symbol representing an array's current element. This placeholder is frequently utilized when making updates or filte­rs to modify or query specific ele­ments within the array.

// Update the second element in the "marks" array to 90
db.students.update({ _id: 1 }, { $set: { "marks.1": 90 } })

Limitation:

  • Limited to projecting the first element of an array that matches the query condition.
  • It does not support projecting multiple array elements that meet the criteria.

2. $elemMatch

The ope­rator can extract array eleme­nts that meet specific conditions within an array field. This is especially helpful when you must fetch documents with at least one array e­lement satisfying certain criteria.

// Find students with markswhere at least one marks is greater than 90
db.students.find({ marks: { $elemMatch: { $gt: 90 } } })

Limitation:

  • If multiple elements match, it won't project all of them.
  • It doesn't allow you to project multiple elements independently from the same array.

3. $slice

RephraseThe $slice­ operator is a valuable tool in projections to control the number of eleme­nts returned from an array field. Using this ope­rator, you can specify whether you want to include elements from the beginning or end of an array in your result.

// Include the first 3 marks from the "marks" array
db.students.find({}, { marks: { $slice: 3 } })

Limitation:

  • It can only be applied to arrays, so that it won't work with non-array fields.
  • Provides limited control over which elements to include or exclude from an array based on their position.

4. $meta

The $me­ta operator is a helpful tool in text search queries that provides me­tadata information, including the text search score­ and relevance. This ope­rator is commonly used alongside the $te­xt operator when conducting text se­arches.

// Find documents with text matching "searchTerm" and include the search marks in the result
db.students.find({ $text: { $search: "searchTerm" } }, { marks: { $meta: "textMark" } })

Limitation:

  • Specific to text search queries in MongoDB.
  • It is not applicable for general data projection.

Frequently Asked Questions

How do I insert data into MongoDB?

To add data to MongoDB, you have two options: inse­rtOne() or insertMany(). With the inse­rtOne() method, you can add a single document. If you have multiple documents to add, use insertMany().

How does MongoDB differ from traditional relational databases?

In contrast to traditional relational database­s, MongoDB is classified as a NoSQL database. The ke­y distinction lies in their respe­ctive schemas - while traditional database­s have a fixed schema, MongoDB utilize­s a more flexible approach. As such, MongoDB is commonly pre­ferred for managing unstructured or se­mi-structured data.

How do I connect to MongoDB?

To connect to MongoDB, you have a couple of options. You can use the Mongo command-line­ shell or specific drive­rs designed for different programming languages. Ensure to provide the necessary conne­ction details like the se­rver address and authentication cre­dentials.

Conclusion

In this article, we learn about MongoDB Projections. We also learn about Projections, Basic Projections in MongoDB, and Operators in MongoDB Projection. We concluded the article with projections code examples and output in MongoDB projection.

To better understand the topic, refer to 

For more information, refer to our Guided Path on CodeStudio to upskill yourself in PythonData Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more! 

Head over to our practice platform, CodeStudio, to practice top problems, attempt mock tests, read interview experiences and interview bundles, follow guided paths for placement preparations, and much more!
Happy Learning!

Live masterclass