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
Querying null value in MongoDB?
To query null value in MongoDB, use $ne operator. Let us first create a collection with documents −
> db.queryingNullDemo.insertOne(
... {
... "StudentName":"Larry",
... "StudentDetails":
... {
... "StudentAge":21,
... "StudentSubject":"MongoDB"
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd00bec588d4a6447b2e05f")
}
> db.queryingNullDemo.insertOne(
... {
... "StudentName":"Sam",
... "StudentDetails":
... {
... "StudentAge":23,
... "StudentSubject":null
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd00c00588d4a6447b2e060")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.queryingNullDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd00bec588d4a6447b2e05f"),
"StudentName" : "Larry",
"StudentDetails" : {
"StudentAge" : 21,
"StudentSubject" : "MongoDB"
}
}
{
"_id" : ObjectId("5cd00c00588d4a6447b2e060"),
"StudentName" : "Sam",
"StudentDetails" : {
"StudentAge" : 23,
"StudentSubject" : null
}
}
Following is how you can query for null −
> db.queryingNullDemo.find({'StudentDetails.StudentSubject': {$ne: null}});
This will produce the following output −
{ "_id" : ObjectId("5cd00bec588d4a6447b2e05f"),
"StudentName" : "Larry",
"StudentDetails" : { "StudentAge" : 21, "StudentSubject" : "MongoDB" } }Advertisements