Tutorialspoint

1 Answer
Nishtha Thakur

Use find() with dot notation to perform recursive search. Let us first create a collection with documents −

> db.findOperationDemo.insertOne({"ClientDetails":[{"ClientId":101,"ClientName":"Chris"},{"ClientId":102,"ClientName":"Robert"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9a118b50a6c6dd317ad99")
}
> db.findOperationDemo.insertOne({"ClientDetails":[{"ClientId":110,"ClientName":"David"},{"ClientId":112,"ClientName":"Mike"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9a12fb50a6c6dd317ad9a")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cd9a118b50a6c6dd317ad99"),
   "ClientDetails" : [
      {
         "ClientId" : 101,
         "ClientName" : "Chris"
      },
      {
         "ClientId" : 102,
         "ClientName" : "Robert"
      }
   ]
}
{
   "_id" : ObjectId("5cd9a12fb50a6c6dd317ad9a"),
   "ClientDetails" : [
      {
         "ClientId" : 110,
         "ClientName" : "David"
      },
      {
         "ClientId" : 112,
         "ClientName" : "Mike"
      }
   ]
}

Following is the query to implement find() for recursive search using dot notation −

> db.findOperationDemo.find({"ClientDetails.ClientId":110});

This will produce the following output −

{ "_id" : ObjectId("5cd9a12fb50a6c6dd317ad9a"), "ClientDetails" : [ { "ClientId" : 110, "ClientName" : "David" }, { "ClientId" : 112, "ClientName" : "Mike" } ] }

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.