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


To check if a field in MongoDB is [] or {}, you can use the following syntax −

db.yourCollectionName.find({
   "yourOuterFieldName": { "$gt": {} },
   "yourOuterFieldName.0": { "$exists": false }
});

Let us first create a collection with documents -

> db.checkFieldDemo.insert([
...   { _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" : [ ]
})

Following is the query to display all documents from a collection with the help of find() method −

> db.checkFieldDemo.find().pretty();

This will produce the following output −

{ "_id" : 1010, "StudentDetails" : { } }
{ "_id" : 1011, "StudentDetails" : [ { "StudentId" : 1 } ] }
{ "_id" : 1012, "StudentDetails" : [ { } ] }
{ "_id" : 1013 }
{ "_id" : 1014, "StudentDetails" : null }
{ "_id" : 1015, "StudentDetails" : { "StudentId" : 1 } }

Following is the query to check if a field in MongoDB is [] or {} −

> db.checkFieldDemo.find({
...   "StudentDetails": { "$gt": {} },
...   "StudentDetails.0": { "$exists": false }
... });

This will produce the following output −

{ "_id" : 1015, "StudentDetails" : { "StudentId" : 1 } }

Updated on: 30-Jul-2019

93 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements