Find a strict document that contains only a specific field with a fixed length?

To find documents containing only specific fields with a fixed length in MongoDB, use the $exists operator combined with $where to check field count. This ensures the document has exactly the required fields and no additional ones.

Syntax

db.collection.find({
    "field1": { $exists: true },
    "field2": { $exists: true },
    $where: function() { return Object.keys(this).length === expectedCount }
});

Sample Data

db.veryStrictDocumentDemo.insertMany([
    {"StudentFirstName": "John", "StudentLastName": "Doe", "StudentAge": 23},
    {"StudentFirstName": "Larry"},
    {"StudentFirstName": "David", "StudentLastName": "Miller"},
    {"StudentFirstName": "Chris"},
    {"StudentFirstName": "Bob", "StudentLastName": "Brown"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cda4bcdb50a6c6dd317adb8"),
        ObjectId("5cda4bdbb50a6c6dd317adb9"),
        ObjectId("5cda4becb50a6c6dd317adba"),
        ObjectId("5cda4bfbb50a6c6dd317adbb"),
        ObjectId("5cda4c6db50a6c6dd317adbc")
    ]
}

Display All Documents

db.veryStrictDocumentDemo.find();
{ "_id" : ObjectId("5cda4bcdb50a6c6dd317adb8"), "StudentFirstName" : "John", "StudentLastName" : "Doe", "StudentAge" : 23 }
{ "_id" : ObjectId("5cda4bdbb50a6c6dd317adb9"), "StudentFirstName" : "Larry" }
{ "_id" : ObjectId("5cda4becb50a6c6dd317adba"), "StudentFirstName" : "David", "StudentLastName" : "Miller" }
{ "_id" : ObjectId("5cda4bfbb50a6c6dd317adbb"), "StudentFirstName" : "Chris" }
{ "_id" : ObjectId("5cda4c6db50a6c6dd317adbc"), "StudentFirstName" : "Bob", "StudentLastName" : "Brown" }

Example: Find Documents with Exactly 4 Fields

To find documents that have exactly StudentFirstName, StudentLastName, and one additional field (besides _id) ?

db.veryStrictDocumentDemo.find({
    "StudentFirstName": { $exists: true },
    "StudentLastName": { $exists: true },
    $where: function() { return Object.keys(this).length === 4 }
});
{ "_id" : ObjectId("5cda4bcdb50a6c6dd317adb8"), "StudentFirstName" : "John", "StudentLastName" : "Doe", "StudentAge" : 23 }

Key Points

  • $exists: true ensures required fields are present
  • $where with Object.keys(this).length validates exact field count
  • The count includes the _id field (MongoDB automatically adds it)
  • This approach filters documents with extra unwanted fields

Conclusion

Use $exists operators for required fields and $where with Object.keys().length to find documents with an exact field count. This ensures strict document structure validation in MongoDB queries.

Updated on: 2026-03-15T01:23:42+05:30

155 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements