
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 in a Dictionary-like Structure by Value with MongoDB
You can use find() for this. Let us first create a collection with documents −
> db.findInDictionaryDemo.insertOne( ... { ... "_id":101, ... "AllCustomerDetails": ... { ... "SomeCustomerDetail1": ... { ... "CustomerName1":"John Doe", ... "CustomerName2":"John Smith" ... }, ... "SomeCustomerDetail2": ... { ... "CustomerName1":"Carol Taylor", ... "CustomerName2":"David Miller" ... } ... } ... } ... ); { "acknowledged" : true, "insertedId" : 101 } > db.findInDictionaryDemo.insertOne( ... { ... "_id":102, ... "AllCustomerDetails": ... { ... "SomeCustomerDetail1": ... { ... "CustomerName1":"Sam Wiliams", ... "CustomerName2":"Bob Johnson" ... }, ... "SomeCustomerDetail2": ... { ... "CustomerName1":"Chris Brown", ... "CustomerName2":"Mike Wilson" ... } ... } ... } ... ); { "acknowledged" : true, "insertedId" : 102 }
Following is the query to display all documents from a collection with the help of find() method −
> db.findInDictionaryDemo.find().pretty();
This will produce the following output −
{ "_id" : 101, "AllCustomerDetails" : { "SomeCustomerDetail1" : { "CustomerName1" : "John Doe", "CustomerName2" : "John Smith" }, "SomeCustomerDetail2" : { "CustomerName1" : "Carol Taylor", "CustomerName2" : "David Miller" } } } { "_id" : 102, "AllCustomerDetails" : { "SomeCustomerDetail1" : { "CustomerName1" : "Sam Wiliams", "CustomerName2" : "Bob Johnson" }, "SomeCustomerDetail2" : { "CustomerName1" : "Chris Brown", "CustomerName2" : "Mike Wilson" } } }
Following is the query to find in dictionary by value in MongoDB −
>db.findInDictionaryDemo.find({"AllCustomerDetails.SomeCustomerDetail2.CustomerName2":"Mike Wilson"}).pretty();
This will produce the following output −
{ "_id" : 102, "AllCustomerDetails" : { "SomeCustomerDetail1" : { "CustomerName1" : "Sam Wiliams", "CustomerName2" : "Bob Johnson" }, "SomeCustomerDetail2" : { "CustomerName1" : "Chris Brown", "CustomerName2" : "Mike Wilson" } } }
Advertisements