MongoDB find() to operate on recursive search?


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

Updated on: 30-Jul-2019

586 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements