How to determine whether a field exists in MongoDB?


You need to use $exists operator to determine whether a field exists in MongoDB. Let us first create a collection with documents

> db.determineFieldExistsDemo.insertOne({"ClientName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9eb245d628fa4220163b75")
}
> db.determineFieldExistsDemo.insertOne({"ClientName":"Larry","ClientAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9eb25cd628fa4220163b76")
}
> db.determineFieldExistsDemo.insertOne({"ClientName":"Mike","ClientCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9eb26fd628fa4220163b77")
}
> db.determineFieldExistsDemo.insertOne({"ClientName":"Sam","ClientAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9eb286d628fa4220163b78")
}

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

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

This will produce the following output

{ "_id" : ObjectId("5c9eb245d628fa4220163b75"), "ClientName" : "John" }
{
   "_id" : ObjectId("5c9eb25cd628fa4220163b76"),
   "ClientName" : "Larry",
   "ClientAge" : 23
}
{
   "_id" : ObjectId("5c9eb26fd628fa4220163b77"),
   "ClientName" : "Mike",
   "ClientCountryName" : "UK"
}
{
   "_id" : ObjectId("5c9eb286d628fa4220163b78"),
   "ClientName" : "Sam",
   "ClientAge" : 24
}

Following is the query to determine whether a field exists

> db.determineFieldExistsDemo.find({ClientCountryName:{$exists:true}}).pretty();

This will produce the following output

{
   "_id" : ObjectId("5c9eb26fd628fa4220163b77"),
   "ClientName" : "Mike",
   "ClientCountryName" : "UK"
}

Updated on: 30-Jul-2019

92 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements