How do I search according to fields in inner classes using MongoDB db.coll.find()?

Use dot notation (.) to search in inner classes (nested objects) using MongoDB. This allows you to query specific fields within embedded documents efficiently.

Syntax

db.collection.find({"outerField.innerField": "value"})

Sample Data

db.searchInInnerDemo.insertMany([
    {
        "StudentFirstName": "Robert",
        "StudentTechnicalDetails": {
            "StudentBackEndTechnology": "MongoDB",
            "StudentLanguage": "Java"
        }
    },
    {
        "StudentFirstName": "David",
        "StudentTechnicalDetails": {
            "StudentBackEndTechnology": "MySQL",
            "StudentLanguage": "PHP"
        }
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cd2dd89b64f4b851c3a13d2"),
        ObjectId("5cd2dda3b64f4b851c3a13d3")
    ]
}

Display all documents from the collection ?

db.searchInInnerDemo.find().pretty();
{
    "_id": ObjectId("5cd2dd89b64f4b851c3a13d2"),
    "StudentFirstName": "Robert",
    "StudentTechnicalDetails": {
        "StudentBackEndTechnology": "MongoDB",
        "StudentLanguage": "Java"
    }
}
{
    "_id": ObjectId("5cd2dda3b64f4b851c3a13d3"),
    "StudentFirstName": "David",
    "StudentTechnicalDetails": {
        "StudentBackEndTechnology": "MySQL",
        "StudentLanguage": "PHP"
    }
}

Case 1: Query Single Nested Property

Search for documents where the nested StudentBackEndTechnology field equals "MongoDB" ?

db.searchInInnerDemo.find({"StudentTechnicalDetails.StudentBackEndTechnology": "MongoDB"}).pretty();
{
    "_id": ObjectId("5cd2dd89b64f4b851c3a13d2"),
    "StudentFirstName": "Robert",
    "StudentTechnicalDetails": {
        "StudentBackEndTechnology": "MongoDB",
        "StudentLanguage": "Java"
    }
}

Case 2: Exact Match on Full Nested Object

Search for documents where the entire nested object matches exactly (field order matters) ?

db.searchInInnerDemo.find({
    "StudentTechnicalDetails": {
        "StudentBackEndTechnology": "MongoDB",
        "StudentLanguage": "Java"
    }
}).pretty();
{
    "_id": ObjectId("5cd2dd89b64f4b851c3a13d2"),
    "StudentFirstName": "Robert",
    "StudentTechnicalDetails": {
        "StudentBackEndTechnology": "MongoDB",
        "StudentLanguage": "Java"
    }
}

Key Points

  • Dot notation allows querying specific nested fields without matching the entire object.
  • Exact object matching requires all fields and their order to match precisely.
  • Use dot notation for flexible queries; use exact matching when you need strict object comparison.

Conclusion

MongoDB's dot notation provides flexible access to nested object fields, while exact object matching offers precise document filtering. Choose the approach based on your specific query requirements.

Updated on: 2026-03-15T01:05:09+05:30

221 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements