Using find() to search for nested keys in MongoDB?

To search for nested keys in MongoDB, use dot notation to specify the path to the nested field. This allows you to query documents based on values within embedded objects.

Syntax

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

Sample Data

Let us create a collection with nested documents ?

db.searchForNestedKeysDemo.insertMany([
    {
        "ClientName": "Larry",
        "ClientAge": 28,
        "ClientExtraDetails": {
            "isEducated": true,
            "CountryName": "US"
        }
    },
    {
        "ClientName": "Chris",
        "ClientAge": 29,
        "ClientExtraDetails": {
            "isEducated": false,
            "CountryName": "UK"
        }
    },
    {
        "ClientName": "David",
        "ClientAge": 39,
        "ClientExtraDetails": {
            "isEducated": true,
            "CountryName": "AUS"
        }
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5ca20e8b66324ffac2a7dc64"),
        ObjectId("5ca20ea366324ffac2a7dc65"),
        ObjectId("5ca20eba66324ffac2a7dc66")
    ]
}

Example: Search by Nested Field

Find all clients from the UK using dot notation ?

db.searchForNestedKeysDemo.find({"ClientExtraDetails.CountryName": "UK"});
{
    "_id": ObjectId("5ca20ea366324ffac2a7dc65"),
    "ClientName": "Chris",
    "ClientAge": 29,
    "ClientExtraDetails": {
        "isEducated": false,
        "CountryName": "UK"
    }
}

Example: Search by Boolean Nested Field

Find all educated clients ?

db.searchForNestedKeysDemo.find({"ClientExtraDetails.isEducated": true});
{
    "_id": ObjectId("5ca20e8b66324ffac2a7dc64"),
    "ClientName": "Larry",
    "ClientAge": 28,
    "ClientExtraDetails": {
        "isEducated": true,
        "CountryName": "US"
    }
}
{
    "_id": ObjectId("5ca20eba66324ffac2a7dc66"),
    "ClientName": "David",
    "ClientAge": 39,
    "ClientExtraDetails": {
        "isEducated": true,
        "CountryName": "AUS"
    }
}

Conclusion

Dot notation enables precise querying of nested fields in MongoDB documents. Simply use the format "outerField.innerField" to access and search within embedded objects efficiently.

Updated on: 2026-03-15T00:42:34+05:30

858 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements