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

Làm cách nào để lấy dữ liệu nhúng trong tài liệu MongoDB?

Sau đây là cú pháp để lấy dữ liệu nhúng trong tài liệu MongoDB

db.yourCollectionName.find({},{‘yourOuterKeyName.yourInnerKeyName:1}).pretty();

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.embeddedCollectionDemo.insertOne(
...    {
...       "StudentName" : "Larry",
...       "StudentDetails": {
...          "Larry1234": {"ProjectName": "Student Web Tracker"},
...          "Larry7645": {"ProjectName": "Hospital Management System"},
...          "Larry9879": {"ProjectName": "Library Management System"},
...
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c98a100330fd0aa0d2fe4c5")
}

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

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

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

{
   "_id" : ObjectId("5c98a100330fd0aa0d2fe4c5"),
   "StudentName" : "Larry",
   "StudentDetails" : {
      "Larry1234" : {
         "ProjectName" : "Student Web Tracker"
      },
      "Larry7645" : {
         "ProjectName" : "Hospital Management System"
      },
      "Larry9879" : {
         "ProjectName" : "Library Management System"
      }
   }
}

Sau đây là truy vấn cho các tập hợp được nhúng, tức là dữ liệu được nhúng trong bộ sưu tập MongoDB

> db.embeddedCollectionDemo.find({},{'StudentDetails.Larry7645':1}).pretty();

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

{
   "_id" : ObjectId("5c98a100330fd0aa0d2fe4c5"),
   "StudentDetails" : {
      "Larry7645" : {
         "ProjectName" : "Hospital Management System"
      }
   }
}