Ignore NULL and UNDEFINED values while running a MongoDB query


To ignore NULL and UNDEFINED values, use $ne in MongoDB. Let us create a collection with documents −

> db.demo35.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e175e42cfb11e5c34d898d0")
}
> db.demo35.insertOne({"Name":null});
{
   "acknowledged" : true,9
   "insertedId" : ObjectId("5e175e46cfb11e5c34d898d1")
}
> db.demo35.insertOne({"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e175e4bcfb11e5c34d898d2")
}
> db.demo35.insertOne({"Name":undefined});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e175e54cfb11e5c34d898d3")
}

Display all documents from a collection with the help of find() method −

> db.demo35.find();

This will produce the following output −

{ "_id" : ObjectId("5e175e42cfb11e5c34d898d0"), "Name" : "Chris" }
{ "_id" : ObjectId("5e175e46cfb11e5c34d898d1"), "Name" : null }
{ "_id" : ObjectId("5e175e4bcfb11e5c34d898d2"), "Name" : "Bob" }
{ "_id" : ObjectId("5e175e54cfb11e5c34d898d3"), "Name" : undefined }

Following is the query to use $new to ignore NULL values −

> db.demo35.find({"Name": {$ne: null}});

This will produce the following output −

{ "_id" : ObjectId("5e175e42cfb11e5c34d898d0"), "Name" : "Chris" }
{ "_id" : ObjectId("5e175e4bcfb11e5c34d898d2"), "Name" : "Bob" }

Updated on: 02-Apr-2020

868 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements