How to check if a field in MongoDB is [] or {}?

To check if a field in MongoDB is an empty array [] or an empty object {}, you can use the $size operator for arrays and $eq operator for objects to identify these specific empty states.

Syntax

// Check for empty object {}
db.collection.find({ "fieldName": {} });

// Check for empty array []
db.collection.find({ "fieldName": { $size: 0 } });

// Check for both empty array or empty object
db.collection.find({
    $or: [
        { "fieldName": {} },
        { "fieldName": { $size: 0 } }
    ]
});

Sample Data

db.checkFieldDemo.insertMany([
    { _id: 1010, StudentDetails: {} },
    { _id: 1011, StudentDetails: [{ StudentId: 1 }] },
    { _id: 1012, StudentDetails: [] },
    { _id: 1013 },
    { _id: 1014, StudentDetails: null },
    { _id: 1015, StudentDetails: { StudentId: 1 } }
]);
BulkWriteResult({
    "writeErrors" : [ ],
    "writeConcernErrors" : [ ],
    "nInserted" : 6,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]
})

Method 1: Check for Empty Object Only

db.checkFieldDemo.find({ "StudentDetails": {} });
{ "_id" : 1010, "StudentDetails" : { } }

Method 2: Check for Empty Array Only

db.checkFieldDemo.find({ "StudentDetails": { $size: 0 } });
{ "_id" : 1012, "StudentDetails" : [ ] }

Method 3: Check for Both Empty Array or Empty Object

db.checkFieldDemo.find({
    $or: [
        { "StudentDetails": {} },
        { "StudentDetails": { $size: 0 } }
    ]
});
{ "_id" : 1010, "StudentDetails" : { } }
{ "_id" : 1012, "StudentDetails" : [ ] }

Key Points

  • {} matches exactly empty objects with no properties
  • { $size: 0 } matches arrays with zero elements
  • $or operator combines both conditions to find either empty arrays or empty objects
  • Fields that are null, undefined, or missing will not match these queries

Conclusion

Use { $size: 0 } for empty arrays and {} for empty objects. Combine them with $or to check for both conditions in a single query, helping you identify documents with empty data structures.

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

227 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements