How can I check whether a field exists or not in MongoDB?


To check whether a field exists or not in MongoDB, you can use the $exists operator.

To understand the above concept, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.checkFieldExistsOrNotDemo.insertOne({"StudentName":"Larry"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92ba4136de59bd9de063a1")
}
> db.checkFieldExistsOrNotDemo.insertOne({"StudentName":"John","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92ba4e36de59bd9de063a2")
}
> db.checkFieldExistsOrNotDemo.insertOne({"StudentName":"Chris","StudentAge":24,"StudentCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92ba6536de59bd9de063a3")
}

> db.checkFieldExistsOrNotDemo.insertOne({"StudentName":"Robert","StudentAge":21,"StudentCountryName":"UK","StudentHobby":["Teaching","Photography"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92ba9d36de59bd9de063a4")
}

Display all documents from a collection with the help of find() method. The query is as follows −

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

The following is the output −

{ "_id" : ObjectId("5c92ba4136de59bd9de063a1"), "StudentName" : "Larry" }
{
   "_id" : ObjectId("5c92ba4e36de59bd9de063a2"),
   "StudentName" : "John",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5c92ba6536de59bd9de063a3"),
   "StudentName" : "Chris",
   "StudentAge" : 24,
   "StudentCountryName" : "US"
}
{
   "_id" : ObjectId("5c92ba9d36de59bd9de063a4"),
   "StudentName" : "Robert",
   "StudentAge" : 21,
   "StudentCountryName" : "UK",
   "StudentHobby" : [
      "Teaching",
      "Photography"
   ]
}

Here is the query to check whether a field exists or not in MongoDB.

Case 1 − When a field exists.

The query is as follows −

> db.checkFieldExistsOrNotDemo.find({ 'StudentHobby' : { '$exists' : true }}).pretty();

The following is the output −

{
   "_id" : ObjectId("5c92ba9d36de59bd9de063a4"),
   "StudentName" : "Robert",
   "StudentAge" : 21,
   "StudentCountryName" : "UK",
   "StudentHobby" : [
      "Teaching",
      "Photography"
   ]
}

Case 2 − When a field does not exist.

The query is as follows:

> db.checkFieldExistsOrNotDemo.find({ 'StudentTechnicalSubject' : { '$exists' : true }}).pretty();

You will not get anything when a field does not exist.

Updated on: 30-Jul-2019

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements