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 select MongoDB document that does not consist a specific field?
Check for a specific field using MongoDB $exists. If that field does not exist in a document, then you need to display the same document with find().
Let us create a collection with documents −
> db.demo612.insertOne({id:1,"Info":[{Name:"Chris",Age:21},{Name:"David"}]});{
"acknowledged" : true, "insertedId" : ObjectId("5e987372f6b89257f5584d87")
}
Display all documents from a collection with the help of find() method −
> db.demo612.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e987372f6b89257f5584d87"),
"id" : 1,
"Info" : [
{
"Name" : "Chris",
"Age" : 21
},
{
"Name" : "David"
}
]
}
Following is the query to fetch a MongoDB document that does not consist of a specific field −
> db.demo612.aggregate({$unwind: "$Info"},
... {$match: {"Info.Age":{$exists: false}}},
... {$project: {"Info.Name": 1}})
This will produce the following output −
{ "_id" : ObjectId("5e987372f6b89257f5584d87"), "Info" : { "Name" : "David" } }Advertisements