MongoDB Query Embedded Documents Using Mongo Shell (original) (raw)

Last Updated : 5 May, 2026

MongoDB stores related data as embedded documents within a single record, unlike a relational database that relies on joins.

Syntax

db.collection.find(filter, projection) 

Example of an Embedded Document

Embed course details inside each student document instead of using separate collections.

Screenshot-2026-02-05-145459

Example 1: Querying Entire Embedded Documents

Retrieving the documents that exactly match the given embedded document.

**Query:

db.Courses.find({name: { first: "Ron", middle: "Rose", last: "Thompson"}})

**Output:

Screenshot-2026-02-05-145817

Example 2: Querying Embedded Documents Using Dot Notation

Query students who are enrolled in Java Backend Development.

**Query:

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

**Output:

Screenshot-2026-02-05-150942

Example 3: Using Query Operators for Advanced Filtering

MongoDB query operators enable advanced filtering for precise and efficient document retrieval.

**1. $in Operator: Match Multiple Values

This operator is used to match any of the values specified in the given array. Find students whose first name is either "Ron" or "Michael".

**Query:

db.Courses.find({"name.first": {$in: ["Ron" , "Michael"]}})

**Output:

Screenshot-2026-02-05-152412

**2. ****$and Operator**: Match Multiple Conditions

Find documents matching nested fields where both conditions are true using $and.

**Query:

db.Courses.find({ $and: [{ "courseDetails.name": "Sudo GATE 2020" }, { "name.first": "Sophia" }] })

**Output:

Screenshot-2026-02-05-155525

Example 4: Selecting Specific Fields with Projections

By default MongoDB returns full documents, use projection to fetch only required fields like first and last names from nested documents.

**Query:

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

**Output:

Screenshot-2026-02-05-155900

Best Practices

Here are some best practices discussed below: