从MongoDB中的嵌套数组中提取特定元素

借助dot(。)表示法从嵌套数组中提取特定元素。首先让我们创建一个包含文档的集合-

> db.extractParticularElementDemo.insertOne(
...    {
...       "_id" : 101,
...       "StudentName" : "John",
...       "StudentInformation" : [
...          {
...             "Age" : 21,
...             "StudentPersonalInformation" : [
...                {
...                   "StudentNickName" : "Mike",
...                   "StudentFamilyDetails" : [
...                      {
...                         "FatherName" : "Carol"
...                      }
...                   ]
...                },
...                {
...                   "StudentAnotherName" : "David",
...                   "StudentFamilyDetails" : [
...                      {
...                         "FatherName" : "Robert"
...                      }
...                   ]
...                }
...             ]
...          }
...       ]
...    }
... );
{ "acknowledged" : true, "insertedId" : 101 }

以下是在find()方法的帮助下显示集合中所有文档的查询-

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

这将产生以下输出-

{
   "_id" : 101,
   "StudentName" : "John",
   "StudentInformation" : [
      {
         "Age" : 21,
         "StudentPersonalInformation" : [
            {
               "StudentNickName" : "Mike",
               "StudentFamilyDetails" : [
                  {
                     "FatherName" : "Carol"
                  }
            ]
         },
         {
            "StudentAnotherName" : "David",
            "StudentFamilyDetails" : [
               {
                  "FatherName" : "Robert"
               }
         ]
      }
   ]
}
]
}

以下是从嵌套数组中提取特定元素的查询-

> db.extractParticularElementDemo.find(
... {'StudentInformation.StudentPersonalInformation.StudentFamilyDetails.FatherName':'Carol'},
... {'StudentInformation.StudentPersonalInformation.StudentFamilyDetails.FatherName':1,"_id":0}
... ).pretty();

这将产生以下输出-

{
   "StudentInformation" : [
      {
         "StudentPersonalInformation" : [
            {
               "StudentFamilyDetails" : [
                  {
                  }
                  "FatherName" : "Carol"
               ]
            },
            {
               "StudentFamilyDetails" : [
                  {
                     "FatherName" : "Robert"
                  }
               ]
            }
         ]
      }
   ]
}