Find documents that contains specific field in MongoDB?

To find documents that contain a specific field in MongoDB, use the $exists operator. This operator checks whether a field exists in a document, regardless of its value.

Syntax

db.collection.find({
    "fieldName": { $exists: true }
});

Sample Data

Let us create a collection with sample documents −

db.findDocumentContainsSpecificFieldDemo.insertMany([
    {
        "ProductPrices": {
            "Product1": 10,
            "Product2": 50
        }
    },
    {
        "ProductPrices": {
            "Product3": 150,
            "Product7": 100,
            "Product5": 250
        }
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cf2385bb64a577be5a2bc14"),
        ObjectId("5cf2387eb64a577be5a2bc15")
    ]
}

Display All Documents

db.findDocumentContainsSpecificFieldDemo.find().pretty();
{
    "_id": ObjectId("5cf2385bb64a577be5a2bc14"),
    "ProductPrices": {
        "Product1": 10,
        "Product2": 50
    }
}
{
    "_id": ObjectId("5cf2387eb64a577be5a2bc15"),
    "ProductPrices": {
        "Product3": 150,
        "Product7": 100,
        "Product5": 250
    }
}

Example: Find Documents with Specific Field

To find documents that contain the field ProductPrices.Product2

db.findDocumentContainsSpecificFieldDemo.find({
    "ProductPrices.Product2": { $exists: true }
});
{
    "_id": ObjectId("5cf2385bb64a577be5a2bc14"),
    "ProductPrices": {
        "Product1": 10,
        "Product2": 50
    }
}

Key Points

  • Use $exists: true to find documents where the field exists
  • Use $exists: false to find documents where the field does not exist
  • Works with nested fields using dot notation

Conclusion

The $exists operator is essential for finding documents containing specific fields. Use dot notation for nested fields and combine with other query operators for complex filtering.

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

208 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements