Using find() to search for nested keys in MongoDB?


For find() to search for nested keys in MongoDB, you can use dot(.) notation. Following is the syntax

db.yourCollectionName.find({"yourOuterFieldName.yourInnerFieldName":"yourValue"}).pretty();

Let us first create a collection with documents:

>db.searchForNestedKeysDemo.insertOne({"ClientName":"Larry","ClientAge":28,"ClientExtra
Details":{"isEducated":true,"CountryName":"US"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca20e8b66324ffac2a7dc64")
}
>db.searchForNestedKeysDemo.insertOne({"ClientName":"Chris","ClientAge":29,"ClientExtra
Details":{"isEducated":false,"CountryName":"UK"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca20ea366324ffac2a7dc65")
}
>db.searchForNestedKeysDemo.insertOne({"ClientName":"David","ClientAge":39,"ClientExtra
Details":{"isEducated":true,"CountryName":"AUS"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca20eba66324ffac2a7dc66")
}

Following is the query to display all documents from a collection with the help of find() method

> db.searchForNestedKeysDemo.find().pretty();

This will produce the following output

{
   "_id" : ObjectId("5ca20e8b66324ffac2a7dc64"),
   "ClientName" : "Larry",
   "ClientAge" : 28,
   "ClientExtraDetails" : {
      "isEducated" : true,
      "CountryName" : "US"
   }
}
{
   "_id" : ObjectId("5ca20ea366324ffac2a7dc65"),
   "ClientName" : "Chris",
   "ClientAge" : 29,
   "ClientExtraDetails" : {
      "isEducated" : false,
      "CountryName" : "UK"
   }
}
{
   "_id" : ObjectId("5ca20eba66324ffac2a7dc66"),
   "ClientName" : "David",
   "ClientAge" : 39,
   "ClientExtraDetails" : {
      "isEducated" : true,
      "CountryName" : "AUS"
   }
}

Following is the query to search for nested keys in MongoDB

> db.searchForNestedKeysDemo.find({"ClientExtraDetails.CountryName":"UK"}).pretty();

This will produce the following output

{
   "_id" : ObjectId("5ca20ea366324ffac2a7dc65"),
   "ClientName" : "Chris",
   "ClientAge" : 29,
   "ClientExtraDetails" : {
      "isEducated" : false,
      "CountryName" : "UK"
   }
}

Updated on: 30-Jul-2019

600 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements