Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" }Advertisements