- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 empty field in a MongoDB collection?
To check empty field in a MongoDB collection, use $exists along with $eq operator. Let us create a collection with documents −
> db.demo485.insertOne({"FirstName":"Chris","LastName":""});{ "acknowledged" : true, "insertedId" : ObjectId("5e82e9f6b0f3fa88e22790a8") } > db.demo485.insertOne({"FirstName":"David","LastName":"Miller"});{ "acknowledged" : true, "insertedId" : ObjectId("5e82e9fdb0f3fa88e22790a9") } > db.demo485.insertOne({"FirstName":"Chris","LastName":"Brown"});{ "acknowledged" : true, "insertedId" : ObjectId("5e82ea03b0f3fa88e22790aa") } > db.demo485.insertOne({"FirstName":"Robert","LastName":""});{ "acknowledged" : true, "insertedId" : ObjectId("5e82ea0fb0f3fa88e22790ab") }
Display all documents from a collection with the help of find() method −
> db.demo485.find();
This will produce the following output −
{ "_id" : ObjectId("5e82e9f6b0f3fa88e22790a8"), "FirstName" : "Chris", "LastName" : "" } { "_id" : ObjectId("5e82e9fdb0f3fa88e22790a9"), "FirstName" : "David", "LastName" : "Miller" } { "_id" : ObjectId("5e82ea03b0f3fa88e22790aa"), "FirstName" : "Chris", "LastName" : "Brown" } { "_id" : ObjectId("5e82ea0fb0f3fa88e22790ab"), "FirstName" : "Robert", "LastName" : "" }
Following is the query to check empty field −
> db.demo485.find({"LastName" : {"$exists" : true, "$eq" : ""}})
This will produce the following output −
{ "_id" : ObjectId("5e82e9f6b0f3fa88e22790a8"), "FirstName" : "Chris", "LastName" : "" } { "_id" : ObjectId("5e82ea0fb0f3fa88e22790ab"), "FirstName" : "Robert", "LastName" : "" }
Advertisements