MongoDB query to fetch a document that does not have a particular field?


To check for existence, use $exists. Let us create a collection with documents − 

> db.demo234.insertOne({"FirstName":"Chris","LastName":"Brown","Age":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e418a50f4cebbeaebec5148")
}
> db.demo234.insertOne({"FirstName":"David","LastName":"Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e418a5ff4cebbeaebec5149")
}
> db.demo234.insertOne({"FirstName":"John","LastName":"Smith",Age:34});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e418a70f4cebbeaebec514a")
}

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

> db.demo234.find();

This will produce the following output −

{ "_id" : ObjectId("5e418a50f4cebbeaebec5148"), "FirstName" : "Chris", "LastName" : "Brown", "Age" : 24 }
{ "_id" : ObjectId("5e418a5ff4cebbeaebec5149"), "FirstName" : "David", "LastName" : "Miller" }
{ "_id" : ObjectId("5e418a70f4cebbeaebec514a"), "FirstName" : "John", "LastName" : "Smith", "Age" : 34 }

Following is the query to check for existence and fetch document without “Age” field −

> var iterator = db.demo234.find({"Age":{$exists:false}},{"_id":0});
> iterator.forEach(function(d)
...{
...   printjson(d);
...})

This will produce the following output −

{ "FirstName" : "David", "LastName" : "Miller" }

Updated on: 30-Mar-2020

434 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements