- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 fetch a document that does not have a particular field?
To check for existence, use $exists. Let us create a collection with documents −
> db.demo234.insertOne({"FirstName":"Chris","LastName":"Brown","Age":24}); { "acknowledged" : true, "insertedId" : ObjectId("5e418a50f4cebbeaebec5148") } > db.demo234.insertOne({"FirstName":"David","LastName":"Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5e418a5ff4cebbeaebec5149") } > db.demo234.insertOne({"FirstName":"John","LastName":"Smith",Age:34}); { "acknowledged" : true, "insertedId" : ObjectId("5e418a70f4cebbeaebec514a") }
Display all documents from a collection with the help of find() method −
> db.demo234.find();
This will produce the following output −
{ "_id" : ObjectId("5e418a50f4cebbeaebec5148"), "FirstName" : "Chris", "LastName" : "Brown", "Age" : 24 } { "_id" : ObjectId("5e418a5ff4cebbeaebec5149"), "FirstName" : "David", "LastName" : "Miller" } { "_id" : ObjectId("5e418a70f4cebbeaebec514a"), "FirstName" : "John", "LastName" : "Smith", "Age" : 34 }
Following is the query to check for existence and fetch document without “Age” field −
> var iterator = db.demo234.find({"Age":{$exists:false}},{"_id":0}); > iterator.forEach(function(d) ...{ ... printjson(d); ...})
This will produce the following output −
{ "FirstName" : "David", "LastName" : "Miller" }
Advertisements