MongoDB query to check the existence of multiple fields


To check the existence of multiple fields, use $exists along with $and. Let us create a collection with documents −

> db.demo475.insertOne({"StudentFirstName":"Chris","StudentAge":23});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e80c113b0f3fa88e2279088")
}
>
db.demo475.insertOne({"StudentFirstName":"Bob","StudentAge":21,"StudentCountryName":"US"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e80c127b0f3fa88e2279089")
}
> db.demo475.insertOne({"StudentFirstName":"David","StudentAge":22});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e80c135b0f3fa88e227908a")
}

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

> db.demo475.find();

This will produce the following output −

{ "_id" : ObjectId("5e80c113b0f3fa88e2279088"), "StudentFirstName" : "Chris", "StudentAge" :
23 }
{ "_id" : ObjectId("5e80c127b0f3fa88e2279089"), "StudentFirstName" : "Bob", "StudentAge" :
21, "StudentCountryName" : "US" }
{ "_id" : ObjectId("5e80c135b0f3fa88e227908a"), "StudentFirstName" : "David", "StudentAge"
: 22 }

Following is the query to check existence of multiple fields −

> db.demo475.find(
... { '$and':
...    [ { 'StudentFirstName': { '$exists': true } },
...       { 'StudentAge': { '$exists': true } },
...       { 'StudentCountryName': { '$exists': true } } ]
...    }
... );

This will produce the following output −

{ "_id" : ObjectId("5e80c127b0f3fa88e2279089"), "StudentFirstName" : "Bob", "StudentAge" :
21, "StudentCountryName" : "US" }

Updated on: 11-May-2020

762 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements