Open In App

MongoDB – Query Embedded Documents Using Mongo Shell

Last Updated : 04 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

MongoDB is a powerful NoSQL database that stores data in a flexible, document-based structure. One of its most useful features is embedded documents, which allow us to store related data inside a single document instead of using multiple collections and performing complex joins.

In this article, we will explain What embedded documents are and why they are useful, How to query embedded documents using dot notation, Advanced querying using operators like $in, $and, $exists.By the end, you’ll have a strong understanding of how to work with embedded documents effectively in MongoDB.

What Are Embedded Documents?

An embedded document (also called a nested document) is a document that is stored inside another document. This is a key feature of MongoDB, allowing for more efficient data retrieval and reducing the need for expensive JOIN operations that are required in relational databases like MySQL or PostgreSQL.

MongoDB provides us with read operations to retrieve embedded/nested documents from the collection or query a collection for an embedded/nested document. We can perform read operations using the db.collection.find() method. This method selects or views embedded/nested documents of the collection and returns the cursor to the selected document.

Syntax:

db.collection.find(filter, projection) 

Parameters: 

  • filter (optional): It specifies the selection filter with the help of query operators. If we want to get all the documents present in the collection, then omit these parameters or pass an empty document in the method.
  • projection (optional): It specifies that only those fields return to the document that matches the given query filter. And if we want to get all the fields in the document, then omit this parameter.

Return:

This method returns a cursor to the documents that match the specified query criteria. When we use find() method, it returns documents, which means the method is actually returning the cursor to the documents.

Example of an Embedded Document

Consider a student database where each student is enrolled in a course. Instead of creating separate collections for students and courses, we embed course details inside the student document.

  • Database: GeeksforGeeks 
  • Collection: Courses 
  • Document: three documents that contain the details of the students in the form of field-value pairs.

Querying Entire Embedded Documents

In this example, we are retrieving the documents that exactly match the given embedded document. To match an entire embedded document, provide the full structure in the exact order it appears in the database.

Query:

python
db.Courses.find({name: {first: "Rohit", 
                        middle: "Kumar", 
                        last: "Singh"}}).pretty()

Output:

Explanation

The field order must exactly match the stored document.
If the middle name is omitted in the query, the document won’t be retrieved.

Querying Embedded Documents Using Dot Notation

In MongoDB, we can access the fields of nested/embedded documents of the collection using dot notation and when we are using dot notation, then the field and the nested field must be inside the quotation marks

Syntax: 

“field.nestedField”: value

Example: Retrieve Students Enrolled in a Specific Course

In this example, we are retrieving the documents that match the specified nested field.  Query students who are enrolled in Java Backend Development:

python
db.Courses.find({"courseDetails.name": "Java Backend Development"}).pretty()

Output:

Explanation:

  • "courseDetails.name" refers to the nested field inside courseDetails.
  • MongoDB retrieves all students where the course name is "Java Backend Development".

Using Query Operators for Advanced Filtering

MongoDB provides query operators to filter documents more efficiently. These operators allow us to perform complex queries, such as searching for multiple values, combining conditions, and checking for field existence. By using these operators, we can retrieve only the most relevant documents, improving query performance and efficiency

1. $in Operator: Match Multiple Values

In this example, we are retrieving the documents that match the nested field using the query operators. Here, in the query, we use $in operator. This operator is used to match any of the values specified in the given array. Find students whose first name is either "Rohit" or "Mohit".

Query:

python
db.Courses.find({"name.first": {$in: ["Rohit", "Mohit"]}}).pretty()

Output:

2. $and Operator: Match Multiple Conditions

In this example, we are retrieving the documents that match the nested fields. The $and operator ensures both conditions must be met for a document to be returned. Find students who belong to the CSE branch and are enrolled in Sudo GATE 2020.

Query:

python
db.Courses.find({"courseDetails.name": "Sudo GATE 2020",
                 "name.first": "Mohit"}).pretty()

Output:

Selecting Specific Fields with Projections

By default, MongoDB returns the entire document. If we only need specific fields, we use projections. In this example, we are retrieving only First and Last Name from the embedded/nested documents using projection

Query:

python
db.Courses.find({branch: "CSE"}, {"name.first": 1, 
                                  "name.last": 1}).pretty()

Output

Best Practices for Querying Embedded Documents

1. Use Indexing for Faster Queries: Index frequently queried fields to improve performance.

db.Courses.createIndex({ "courseDetails.name": 1 })

2. Use Projections to Minimize Data Transfer: Fetch only the necessary fields to reduce network load.

3. Avoid Deep Nesting: Excessive nesting can slow down queries. Flatten data where possible.

4. Use $exists to Check Missing Fields: Ensure fields exist before querying to prevent errors.

Conclusion

Embedded documents in MongoDB provide a powerful way to store and manage structured data within a single document, eliminating the need for complex joins that are common in relational databases. By understanding how to efficiently query embedded documents using dot notation, query operators like $in, $and, and $exists, and projections for selective field retrieval, developers can optimize data retrieval and improve application performance. Mastering these techniques ensures a strong foundation for working with MongoDB, enabling developers to build scalable and high-performance applications.



Next Article
Article Tags :

Similar Reads