MongoDB query which represents not equal to null or empty?

MongoDBDatabaseBig Data Analytics

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
}
raja
Published on 12-Apr-2019 07:45:53
Advertisements