Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 } }Advertisements