- 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
Filter documents in MongoDB if all keys exist as fields?
For this, use $all, that would find documents containing all of the elements in an array like "keys". Let us first create a collection with documents −
> db.demo17.insertOne({"ListOfSubject":["MySQL","MongoDB","Java"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e13847255d0fc6657d21f0a") } > db.demo17.insertOne({"ListOfSubject":["C","Python","Java"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e13847e55d0fc6657d21f0b") } > db.demo17.insertOne({"ListOfSubject":["C++","MongoDB","PL/SQL"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e13849255d0fc6657d21f0c") }
Following is the query to display all documents from a collection with the help of find() method −
> db.demo17.find();
This will produce the following output −
{ "_id" : ObjectId("5e13847255d0fc6657d21f0a"), "ListOfSubject" : [ "MySQL", "MongoDB", "Java" ] } { "_id" : ObjectId("5e13847e55d0fc6657d21f0b"), "ListOfSubject" : [ "C", "Python", "Java" ] } { "_id" : ObjectId("5e13849255d0fc6657d21f0c"), "ListOfSubject" : [ "C++", "MongoDB", "PL/SQL" ] }
Here is the query to filter documents if all keys exist as fields −
> db.demo17.find({"ListOfSubject": { "$all": ["C++","PL/SQL","MongoDB"] } });
This will produce the following output −
{ "_id" : ObjectId("5e13849255d0fc6657d21f0c"), "ListOfSubject" : [ "C++", "MongoDB", "PL/SQL" ] }
Advertisements