MongoDB query to determine if a specific value does not exist?


To determine if a specific value does not exist, use $ne in MongoDB. Let us create a collection with documents −

> db.demo206.insertOne(
...   {
...      "ClientDetails":
...      [
...         {
...            "Name":"Chris",
...            "Age":28,
...            "CountryName":"US"
...         }
...      ]
...   }
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3d8bd403d395bdc21346ee")
}
> db.demo206.insertOne(
...   {
...      "ClientDetails":
...      [
...         {
...            "Name":"David",
...            "Age":29,
...            "CountryName":"UK"
...         }
...      ]
...   }
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3d8bd403d395bdc21346ef")
}
>
> db.demo206.insertOne(
...   {
...      "ClientDetails":
...      [
...         {
...            "Name":"Bob",
...            "Age":31,
...            "CountryName":"US"
...         }
...      ]
...   }
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3d8bd503d395bdc21346f0")
}

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

> db.demo206.find();

This will produce the following output −

{ "_id" : ObjectId("5e3d8bd403d395bdc21346ee"), "ClientDetails" : [ { "Name" : "Chris", "Age" : 28, "CountryName" : "US" } ] }
{ "_id" : ObjectId("5e3d8bd403d395bdc21346ef"), "ClientDetails" : [ { "Name" : "David", "Age" : 29, "CountryName" : "UK" } ] }
{ "_id" : ObjectId("5e3d8bd503d395bdc21346f0"), "ClientDetails" : [ { "Name" : "Bob", "Age" : 31, "CountryName" : "US" } ] }

Following is the query to determine if a specific value does not exist −

> db.demo206.find({"ClientDetails.CountryName": {"$ne": "US"}});

This will produce the following output −

{ "_id" : ObjectId("5e3d8bd403d395bdc21346ef"), "ClientDetails" : [ { "Name" : "David", "Age" : 29, "CountryName" : "UK" } ] }

Updated on: 27-Mar-2020

236 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements