

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 } }
- Related Questions & Answers
- How to check if field is a number in MongoDB?
- How to check if field is null or empty in MySQL?
- How to check if a text field is empty or not in swift?
- Check if a field contains a string in MongoDB?
- Check whether field exist in MongoDB or not?
- How can I check whether a field exists or not in MongoDB?
- Check if value exists for a field in a MongoDB document?
- How to check empty field in a MongoDB collection?
- Check whether a field is empty or null in MySQL?
- JavaScript: How to check if a number is NaN or finite?
- How to apply a condition only if field exists in MongoDB?
- Check if a list is not empty in MongoDB?
- How to check if a matrix is invertible or not in R?
- How to Check if a Number is Odd or Even using Python?
- PyTorch – How to check if a tensor is contiguous or not?
Advertisements