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
How to find a document by the non-existence of a field in MongoDB?
To find a document by the non-existence of a field in MongoDB, the syntax is as follows −
db.yourCollectionName.find({ "yourFieldName" : { "$exists" : false } }).pretty();
To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.findDocumentNonExistenceFieldDemo.insertOne({"StudentName":"John","StudentAge":25});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8a5c629064dcd4a68b70e8")
}
> db.findDocumentNonExistenceFieldDemo.insertOne({"StudentName":"David","StudentAge":26,"StudentMathMarks":78});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8a5c809064dcd4a68b70e9")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.findDocumentNonExistenceFieldDemo.find().pretty();
The following is the output −
{
"_id" : ObjectId("5c8a5c629064dcd4a68b70e8"),
"StudentName" : "John",
"StudentAge" : 25
}
{
"_id" : ObjectId("5c8a5c809064dcd4a68b70e9"),
"StudentName" : "David",
"StudentAge" : 26,
"StudentMathMarks" : 78
}
Here is the query to find a document by the non-existence of a field −
> db.findDocumentNonExistenceFieldDemo.find({ "StudentMathMarks" : { "$exists" : false } }).pretty();
The following is the output −
{
"_id" : ObjectId("5c8a5c629064dcd4a68b70e8"),
"StudentName" : "John",
"StudentAge" : 25
}Advertisements