MongoDB query to check the existence of multiple fields

To check the existence of multiple fields in MongoDB, use the $exists operator combined with $and. This query returns documents that contain all specified fields.

Syntax

db.collection.find({
    $and: [
        { "field1": { $exists: true } },
        { "field2": { $exists: true } },
        { "field3": { $exists: true } }
    ]
});

Sample Data

db.demo475.insertMany([
    { "StudentFirstName": "Chris", "StudentAge": 23 },
    { "StudentFirstName": "Bob", "StudentAge": 21, "StudentCountryName": "US" },
    { "StudentFirstName": "David", "StudentAge": 22 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e80c113b0f3fa88e2279088"),
        ObjectId("5e80c127b0f3fa88e2279089"),
        ObjectId("5e80c135b0f3fa88e227908a")
    ]
}

Display all documents from the collection ?

db.demo475.find();
{ "_id": ObjectId("5e80c113b0f3fa88e2279088"), "StudentFirstName": "Chris", "StudentAge": 23 }
{ "_id": ObjectId("5e80c127b0f3fa88e2279089"), "StudentFirstName": "Bob", "StudentAge": 21, "StudentCountryName": "US" }
{ "_id": ObjectId("5e80c135b0f3fa88e227908a"), "StudentFirstName": "David", "StudentAge": 22 }

Example: Check Multiple Field Existence

Find documents that have all three fields: StudentFirstName, StudentAge, and StudentCountryName ?

db.demo475.find({
    $and: [
        { "StudentFirstName": { $exists: true } },
        { "StudentAge": { $exists: true } },
        { "StudentCountryName": { $exists: true } }
    ]
});
{ "_id": ObjectId("5e80c127b0f3fa88e2279089"), "StudentFirstName": "Bob", "StudentAge": 21, "StudentCountryName": "US" }

Key Points

  • $exists: true matches documents where the field exists, regardless of value (including null).
  • $and ensures ALL specified fields must exist in the document.
  • Only the "Bob" document contains all three fields, so it's the only result returned.

Conclusion

Use $and with multiple $exists conditions to find documents containing all required fields. This is useful for data validation and ensuring document completeness before processing.

Updated on: 2026-03-15T03:06:11+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements