How can I search a collection to find a nested value in one of its documents in MongoDB?

To search for nested values in MongoDB documents, use dot notation in the find() method. This allows you to query fields within embedded objects by specifying the path to the nested field.

Syntax

db.collection.find({"parentField.nestedField": "value"});

Sample Data

Let us first create a collection with nested documents ?

db.nestedDemo.insertMany([
    {"Information": {"__StudentName": "John Smith"}},
    {"Information": {"__StudentName": "John Doe"}},
    {"Information": {"__StudentName": "Chris Brown"}}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e06f39125ddae1f53b621f0"),
        ObjectId("5e06f39e25ddae1f53b621f1"),
        ObjectId("5e06f3a625ddae1f53b621f2")
    ]
}

Display all documents to verify the structure ?

db.nestedDemo.find().pretty();
{
    "_id": ObjectId("5e06f39125ddae1f53b621f0"),
    "Information": {
        "__StudentName": "John Smith"
    }
}
{
    "_id": ObjectId("5e06f39e25ddae1f53b621f1"),
    "Information": {
        "__StudentName": "John Doe"
    }
}
{
    "_id": ObjectId("5e06f3a625ddae1f53b621f2"),
    "Information": {
        "__StudentName": "Chris Brown"
    }
}

Example: Search for Nested Value

Search for a specific nested value using dot notation ?

db.nestedDemo.find({"Information.__StudentName": "John Doe"});
{ "_id": ObjectId("5e06f39e25ddae1f53b621f1"), "Information": { "__StudentName": "John Doe" } }

Key Points

  • Use dot notation to access nested fields: "parentField.childField"
  • Field names with special characters (like underscores) work normally in dot notation
  • The query returns only documents where the nested field matches the specified value

Conclusion

Dot notation provides a simple way to query nested document fields in MongoDB. Use the format "parentField.nestedField" in your find() queries to search for specific values within embedded objects.

Updated on: 2026-03-15T02:05:17+05:30

156 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements