Find the document by field name with a specific value in MongoDB?

To find documents by field name with a specific value in MongoDB, you can use the $exists operator to check if a field exists, or use dot notation to match specific field values in nested documents.

Syntax

// Check if field exists
db.collection.find({"fieldName": {$exists: true}})

// Find by specific value in nested field
db.collection.find({"parent.child": "specificValue"})

Sample Data

db.findByFieldName.insertMany([
    {
        "Client": {
            "ClientDetails": {
                "ClientName": "Larry",
                "ClientAge": 29
            },
            "ClientProjectDetails": {
                "ProjectName": "Online Book Store",
                "TeamSize": 10,
                "TechnologyUsed": "Spring Boot"
            }
        }
    },
    {
        "Client": {
            "ClientDetails": {
                "ClientName": "Chris",
                "ClientAge": 27
            },
            "ClientEducationDetails": {
                "isEducated": true,
                "CollegeName": "M.I.T."
            }
        }
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("..."),
        ObjectId("...")
    ]
}

Example 1: Find Documents Where Field Exists

Find all documents that have the "ClientProjectDetails" field ?

db.findByFieldName.find({"Client.ClientProjectDetails": {$exists: true}});
{
    "_id": ObjectId("5c9e93b2d628fa4220163b64"),
    "Client": {
        "ClientDetails": {
            "ClientName": "Larry",
            "ClientAge": 29
        },
        "ClientProjectDetails": {
            "ProjectName": "Online Book Store",
            "TeamSize": 10,
            "TechnologyUsed": "Spring Boot"
        }
    }
}

Example 2: Find by Specific Field Value

Find documents where ClientName is "Chris" ?

db.findByFieldName.find({"Client.ClientDetails.ClientName": "Chris"});
{
    "_id": ObjectId("5c9e9421d628fa4220163b65"),
    "Client": {
        "ClientDetails": {
            "ClientName": "Chris",
            "ClientAge": 27
        },
        "ClientEducationDetails": {
            "isEducated": true,
            "CollegeName": "M.I.T."
        }
    }
}

Key Points

  • $exists: true finds documents where the specified field exists
  • $exists: false finds documents where the field does not exist
  • Use dot notation to access nested fields: "parent.child.field"

Conclusion

Use $exists to find documents by field presence, or dot notation with specific values to match nested field content. Both approaches help filter documents based on field structure and values.

Updated on: 2026-03-15T00:38:20+05:30

691 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements