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"
      }
   }
}

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements