Computer >> Máy Tính >  >> Lập trình >> MongoDB

Trích xuất một phần tử cụ thể từ một mảng lồng nhau trong MongoDB

Trích xuất một phần tử cụ thể từ một mảng lồng nhau với sự trợ giúp của ký hiệu dấu chấm (.). Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -

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

Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -

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

Điều này sẽ tạo ra kết quả sau -

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

Sau đây là truy vấn để trích xuất phần tử cụ thể từ một mảng lồng nhau -

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

Điều này sẽ tạo ra kết quả sau -

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