Search a sub-field on MongoDB?

To search a sub-field in MongoDB, use dot notation with the field path enclosed in double quotes. This allows you to query nested fields within embedded documents.

Syntax

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

Sample Data

db.searchSubFieldDemo.insertMany([
    {
        "UserDetails": {
            "UserEmailId": "John123@gmail.com",
            "UserAge": 21
        }
    },
    {
        "UserDetails": {
            "UserEmailId": "Carol@yahoo.com",
            "UserAge": 26
        }
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cd3d909edc6604c74817ce2"),
        ObjectId("5cd3d9a4edc6604c74817ce3")
    ]
}

View All Documents

db.searchSubFieldDemo.find();
{
    "_id": ObjectId("5cd3d909edc6604c74817ce2"),
    "UserDetails": {
        "UserEmailId": "John123@gmail.com",
        "UserAge": 21
    }
}
{
    "_id": ObjectId("5cd3d9a4edc6604c74817ce3"),
    "UserDetails": {
        "UserEmailId": "Carol@yahoo.com",
        "UserAge": 26
    }
}

Example: Search by Sub-field

Find the document where UserEmailId is "Carol@yahoo.com" ?

db.searchSubFieldDemo.find({"UserDetails.UserEmailId": "Carol@yahoo.com"});
{
    "_id": ObjectId("5cd3d9a4edc6604c74817ce3"),
    "UserDetails": {
        "UserEmailId": "Carol@yahoo.com",
        "UserAge": 26
    }
}

Conclusion

Use dot notation with quoted field paths to search nested sub-fields in MongoDB. The syntax "parentField.subField" allows precise querying of embedded document properties.

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

339 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements