Tutorialspoint

1 Answer
Anvi Jain

We will use the Null type here. Following are the null types with the alias −

TypeNumberAlias
Double1“double”
String2“string”
Object3“object”
Array4“array”
Binary data5“binData”
Undefined6“undefined”
ObjectId7“objectId”
Boolean8“bool”
Date9“date”
Null10“null”
Regular Expression11“regex”

Following is the syntax for type 10 i.e. null −

db.yourCollectionName.find({"yourFieldName":{ $type: 10 } });

The above syntax will find only those documents which have null value. Let us first create a collection with documents −

> db.mongoDbEqualDemo.insertOne({"Age":34});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7e9121a844af18acdffa3")
}
> db.mongoDbEqualDemo.insertOne({"Age":""});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7e9161a844af18acdffa4")
}
> db.mongoDbEqualDemo.insertOne({"Age":null});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7e9191a844af18acdffa5")
}
> db.mongoDbEqualDemo.insertOne({"Age":56});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7e91e1a844af18acdffa6")
}
> db.mongoDbEqualDemo.insertOne({});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7e9261a844af18acdffa7")
}
> db.mongoDbEqualDemo.insertOne({"Age":null});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7e92e1a844af18acdffa8")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.mongoDbEqualDemo.find().pretty();

This will produce the following output −

{ "_id" : ObjectId("5cd7e9121a844af18acdffa3"), "Age" : 34 }
{ "_id" : ObjectId("5cd7e9161a844af18acdffa4"), "Age" : "" }
{ "_id" : ObjectId("5cd7e9191a844af18acdffa5"), "Age" : null }
{ "_id" : ObjectId("5cd7e91e1a844af18acdffa6"), "Age" : 56 }
{ "_id" : ObjectId("5cd7e9261a844af18acdffa7") }
{ "_id" : ObjectId("5cd7e92e1a844af18acdffa8"), "Age" : null }

Following is the query to check for equal to null values only −

> db.mongoDbEqualDemo.find({"Age":{ $type: 10 } });

This will produce the following output −

{ "_id" : ObjectId("5cd7e9191a844af18acdffa5"), "Age" : null }
{ "_id" : ObjectId("5cd7e92e1a844af18acdffa8"), "Age" : null }

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.