Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How do I check whether a field contains null value in MongoDB?
You can use $type operator to check whether a filed contains null value. Let us first create a collection with documents. We have also inserted a null in a field −
> db.nullDemo.insertOne({"FirstName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc68a1eac184d684e3fa270")
}
> db.nullDemo.insertOne({"FirstName":null});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc68a25ac184d684e3fa271")
}
> db.nullDemo.insertOne({"FirstName":"Robert"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc68a2cac184d684e3fa272")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.nullDemo.find().pretty();
This will produce the following output. One of the field is null −
{ "_id" : ObjectId("5cc68a1eac184d684e3fa270"), "FirstName" : "Chris" }
{ "_id" : ObjectId("5cc68a25ac184d684e3fa271"), "FirstName" : null }
{ "_id" : ObjectId("5cc68a2cac184d684e3fa272"), "FirstName" : "Robert" }
Here is the query to check whether a field contains null value. The field “FirstName” is checked −
> db.nullDemo.find( { FirstName: { $type: 10 } } );
This will produce the following output −
{ "_id" : ObjectId("5cc68a25ac184d684e3fa271"), "FirstName" : null } Advertisements
