

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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" }
- Related Questions & Answers
- MongoDB query for exact match on multiple document fields
- MongoDB query to sum specific fields
- MongoDB query to update selected fields
- Search multiple fields for multiple values in MongoDB?
- MongoDB query condition to compare two fields?
- MongoDB query to update only certain fields?
- MongoDB query to exclude both the fields with FALSE
- MongoDB query with fields in the same document?
- Prevent duplicates of multiple fields with index in MongoDB
- MongoDB query to concatenate values of array with other fields
- Performing distinct on multiple fields in MongoDB?
- Count by multiple fields with MongoDB aggregation
- MongoDB query to display all the fields value, except _id
- MongoDB query to add multiple documents
- MongoDB query condition on comparing 2 fields?
Advertisements