How can I use MongoDB to find all documents which have a field, regardless of the value of that field?


To use MongoDB to find all documents which have a field, regardless of the value of that field, use the $exists operator. Following is the syntax

db.yourCollectionName.find({yourFieldName:{$exists:true}});

Let us create a collection with documents

>db.findAllDocumentWhichHaveFieldDemo.insertOne({"StudentName":"John","StudentAge":null});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9d1d60a629b87623db1b22")
}
>db.findAllDocumentWhichHaveFieldDemo.insertOne({"StudentName":"Larry","StudentAge":null});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9d1d70a629b87623db1b23")
}
>db.findAllDocumentWhichHaveFieldDemo.insertOne({"StudentName":"Chris","StudentAge":""});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9d1d7ba629b87623db1b24")
}
>db.findAllDocumentWhichHaveFieldDemo.insertOne({"StudentName":"Robert","StudentAge":""});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9d1d81a629b87623db1b25")
}

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

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

This will produce the following output

{
   "_id" : ObjectId("5c9d1d60a629b87623db1b22"),
   "StudentName" : "John",
   "StudentAge" : null
}
{
   "_id" : ObjectId("5c9d1d70a629b87623db1b23"),
   "StudentName" : "Larry",
   "StudentAge" : null
}
{
   "_id" : ObjectId("5c9d1d7ba629b87623db1b24"),
   "StudentName" : "Chris",
   "StudentAge" : ""
}
{
   "_id" : ObjectId("5c9d1d81a629b87623db1b25"),
   "StudentName" : "Robert",
   "StudentAge" : ""
}

Following is the query to use MongoDB to find all documents which have a field, regardless of the value of that field

> db.findAllDocumentWhichHaveFieldDemo.find({StudentAge:{$exists:true}});

This will produce the following output

{ "_id" : ObjectId("5c9d1d60a629b87623db1b22"), "StudentName" : "John", "StudentAge" : null }
{ "_id" : ObjectId("5c9d1d70a629b87623db1b23"), "StudentName" : "Larry", "StudentAge" : null }
{ "_id" : ObjectId("5c9d1d7ba629b87623db1b24"), "StudentName" : "Chris", "StudentAge" : "" }
{ "_id" : ObjectId("5c9d1d81a629b87623db1b25"), "StudentName" : "Robert", "StudentAge" : "" }

Following is the query if you do not want the field “StudentName” in the result

>db.findAllDocumentWhichHaveFieldDemo.find({},{StudentName:0},{StudentAge:{$exists:true}});

This will produce the following output

{ "_id" : ObjectId("5c9d1d60a629b87623db1b22"), "StudentAge" : null }
{ "_id" : ObjectId("5c9d1d70a629b87623db1b23"), "StudentAge" : null }
{ "_id" : ObjectId("5c9d1d7ba629b87623db1b24"), "StudentAge" : "" }
{ "_id" : ObjectId("5c9d1d81a629b87623db1b25"), "StudentAge" : "" }

Updated on: 30-Jul-2019

58 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements