Find items that do not have a certain field in MongoDB?


To find items that do not have a certain field, use the $exists operator. The syntax is as follows −

> db.yourCollectionName.find({"yourItemName":{$exists:false}}).pretty();

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

> db.findDocumentDoNotHaveCertainFields.insertOne({"UserId":101,"UserName":"John","UserAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a95fb6cea1f28b7aa07fb")
}
> db.findDocumentDoNotHaveCertainFields.insertOne({"UserName":"David","UserAge":22,"UserFavouriteSubject":["C","Java"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a96116cea1f28b7aa07fc")
}
> db.findDocumentDoNotHaveCertainFields.insertOne({"UserName":"Bob","UserAge":24,"UserFavouriteSubject":["MongoDB","MySQL"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a96306cea1f28b7aa07fd")
}

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

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

The following is the output −

{
   "_id" : ObjectId("5c8a95fb6cea1f28b7aa07fb"),
   "UserId" : 101,
   "UserName" : "John",
   "UserAge" : 21
}
{
   "_id" : ObjectId("5c8a96116cea1f28b7aa07fc"),
   "UserName" : "David",
   "UserAge" : 22,
   "UserFavouriteSubject" : [
      "C",
      "Java"
   ]
}
{
   "_id" : ObjectId("5c8a96306cea1f28b7aa07fd"),
   "UserName" : "Bob",
   "UserAge" : 24,
   "UserFavouriteSubject" : [
      "MongoDB",
      "MySQL"
   ]
}

Here is the query to find items that do not have certain field i.e. UserFavouriteSubject −

> db.findDocumentDoNotHaveCertainFields.find({"UserFavouriteSubject":{$exists:false}}).pretty();

The following is the output −

{
   "_id" : ObjectId("5c8a95fb6cea1f28b7aa07fb"),
   "UserId" : 101,
   "UserName" : "John",
   "UserAge" : 21
}

Updated on: 30-Jul-2019

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements