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
Find documents that contains specific field in MongoDB?
For this, use the $exists operator. Let us first create a collection with documents −
>dbfindDocumentContainsSpecificFieldDemoinsertOne({"ProductPrices":{"Product1":10,"Pr oduct2":50}});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cf2385bb64a577be5a2bc14")
}
>dbfindDocumentContainsSpecificFieldDemoinsertOne({"ProductPrices":{"Product3":150,"P roduct7":100,"Product5":250}});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cf2387eb64a577be5a2bc15")
}
Following is the query to display all documents from a collection with the help of find() method −
> dbfindDocumentContainsSpecificFieldDemofind()pretty();
This will produce the following document −
{
"_id" : ObjectId("5cf2385bb64a577be5a2bc14"),
"ProductPrices" : {
"Product1" : 10,
"Product2" : 50
}
}
{
"_id" : ObjectId("5cf2387eb64a577be5a2bc15"),
"ProductPrices" : {
"Product3" : 150,
"Product7" : 100,
"Product5" : 250
}
}
Following is the query to find documents that contains specific field −
> dbfindDocumentContainsSpecificFieldDemofind({"ProductPricesProduct2":{$exists:true}});
This will produce the following document −
{ "_id" : ObjectId("5cf2385bb64a577be5a2bc14"), "ProductPrices" : { "Product1" : 10, "Product2" : 50 } }Advertisements