Search for a text in MongoDBs Double Nested Array?


Search for a text in MongoDBs Double Nested Array with the help of dot(.) notation. Let us first create a collection. Following is the query to create a collection with documents

> db.doubleNestedArrayDemo.insertOne(
...    {
...       "StudentId" : "1000",
...       "StudentName" : "Larry",
...       "StudentDetails" : [
...          {
...             "ProjectName" : "Online Banking",
...             "ProjectDetails" : [
...                {
...                   "TechnologyUsed" : "Java"
...                },
...                {
...                   "TechnologyUsed" : "MySQL in Backend"
...                }
...             ]
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c992bd7330fd0aa0d2fe4cc")
}
> db.doubleNestedArrayDemo.insertOne( { "StudentId" : "1001", "StudentName" : "Robert", "StudentDetails" : [ { "ProjectName" : "Student Web Tracker", "ProjectDetails" : [ { "TechnologyUsed" : "Django Framework" }, { "TechnologyUsed" : "MongoDB in Backend" } ] } ] } );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c992cdb330fd0aa0d2fe4cd")
}

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

> db.doubleNestedArrayDemo.find().pretty()

This will produce the following output

{
   "_id" : ObjectId("5c992bd7330fd0aa0d2fe4cc"),
   "StudentId" : "1000",
   "StudentName" : "Larry",
   "StudentDetails" : [
      {
         "ProjectName" : "Online Banking",
         "ProjectDetails" : [
            {
               "TechnologyUsed" : "Java"
            },
            {
               "TechnologyUsed" : "MySQL in Backend"
            }
         ]
      }
   ]
}
{
   "_id" : ObjectId("5c992cdb330fd0aa0d2fe4cd"),
   "StudentId" : "1001",
   "StudentName" : "Robert",
   "StudentDetails" : [
      {
         "ProjectName" : "Student Web Tracker",
         "ProjectDetails" : [
            {
               "TechnologyUsed" : "Django Framework"
            },
            {
               "TechnologyUsed" : "MongoDB in Backend"
            }
         ]
      }
   ]
}

Following is the query to search in a double nested array. We are finding the record with text “Java”

>db.doubleNestedArrayDemo.find({"StudentDetails.ProjectDetails.TechnologyUsed":"Java"}).pretty();

This will produce the following output

{
   "_id" : ObjectId("5c992bd7330fd0aa0d2fe4cc"),
   "StudentId" : "1000",
   "StudentName" : "Larry",
   "StudentDetails" : [
      {
         "ProjectName" : "Online Banking",
         "ProjectDetails" : [
            {
               "TechnologyUsed" : "Java"
            },
            {
               "TechnologyUsed" : "MySQL in Backend"
            }
         ]
      }
   ]
}

Updated on: 30-Jul-2019

77 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements