Implementing MongoDB $exists and $ne?


The $exists is used to check whethre a filed exists, whereas $ne is for not equal condition. Let us first create a collection with documents −

> db.existsDemo.insertOne({"Name":"Chris","Age":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7c3916d78f205348bc650")
}
> db.existsDemo.insertOne({"Name":"","Age":null});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7c39a6d78f205348bc651")
}
> db.existsDemo.insertOne({"Name":null,"Age":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7c3a66d78f205348bc652")
}
> db.existsDemo.insertOne({"Age":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7c3c36d78f205348bc653")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cd7c3916d78f205348bc650"),
   "Name" : "Chris",
   "Age" : 21
}
{ "_id" : ObjectId("5cd7c39a6d78f205348bc651"), "Name" : "", "Age" : null }
{ "_id" : ObjectId("5cd7c3a66d78f205348bc652"), "Name" : null, "Age" : 24 }
{ "_id" : ObjectId("5cd7c3c36d78f205348bc653"), "Age" : 23 }

Following is the query to implement $exists operator −

> db.existsDemo.find({"$and":[ {"Name":{"$exists":true}}, {"Name":{"$ne": ""}}]});

This will produce the following output −

{ "_id" : ObjectId("5cd7c3916d78f205348bc650"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5cd7c3a66d78f205348bc652"), "Name" : null, "Age" : 24 }

Updated on: 30-Jul-2019

266 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements