
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
MongoDB Query for Not Equal to Null or Empty
To set a query for not equal to null or empty, use the $nin operator. The syntax is as follows
db.yourCollectionName.find({yourFieldName:{$nin:[null,""]}});
Let us create a collection with documents
> db.notEqualToNullOrEmptyDemo.insertOne({"UserName":"Larry","UserAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5c9d20b6a629b87623db1b26") } > db.notEqualToNullOrEmptyDemo.insertOne({"UserName":"","UserAge":29}); { "acknowledged" : true, "insertedId" : ObjectId("5c9d20bea629b87623db1b27") } > db.notEqualToNullOrEmptyDemo.insertOne({"UserName":"Sam","UserAge":32}); { "acknowledged" : true, "insertedId" : ObjectId("5c9d20c7a629b87623db1b28") } > db.notEqualToNullOrEmptyDemo.insertOne({"UserName":null,"UserAge":27}); { "acknowledged" : true, "insertedId" : ObjectId("5c9d20d2a629b87623db1b29") } > db.notEqualToNullOrEmptyDemo.insertOne({"UserName":"Robert","UserAge":26}); { "acknowledged" : true, "insertedId" : ObjectId("5c9d20dda629b87623db1b2a") } > db.notEqualToNullOrEmptyDemo.insertOne({"UserName":"","UserAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c9d20e7a629b87623db1b2b") }
Following is the query to display all documents from a collection with the help of find() method
> db.notEqualToNullOrEmptyDemo.find().pretty();
This will produce the following output
{ "_id" : ObjectId("5c9d20b6a629b87623db1b26"), "UserName" : "Larry", "UserAge" : 24 } { "_id" : ObjectId("5c9d20bea629b87623db1b27"), "UserName" : "", "UserAge" : 29 } { "_id" : ObjectId("5c9d20c7a629b87623db1b28"), "UserName" : "Sam", "UserAge" : 32 } { "_id" : ObjectId("5c9d20d2a629b87623db1b29"), "UserName" : null, "UserAge" : 27 } { "_id" : ObjectId("5c9d20dda629b87623db1b2a"), "UserName" : "Robert", "UserAge" : 26 } { "_id" : ObjectId("5c9d20e7a629b87623db1b2b"), "UserName" : "", "UserAge" : 23 }
Following is the query to set condition for not equal to null or empty
> db.notEqualToNullOrEmptyDemo.find({UserName:{$nin:[null,""]}}).pretty();
This will produce the following output
{ "_id" : ObjectId("5c9d20b6a629b87623db1b26"), "UserName" : "Larry", "UserAge" : 24 } { "_id" : ObjectId("5c9d20c7a629b87623db1b28"), "UserName" : "Sam", "UserAge" : 32 } { "_id" : ObjectId("5c9d20dda629b87623db1b2a"), "UserName" : "Robert", "UserAge" : 26 }
Advertisements