如何獲取 MongoDB 文件中的嵌入式資料?


以下是獲取 MongoDB 文件中嵌入式資料所需的語法

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

讓我們先建立包含文件的集合

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

以下是顯示集合中所有文件的查詢

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

這將產生以下輸出

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

以下是嵌入式集合(即 MongoDB 集合中的嵌入式資料)的查詢

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

這將產生以下輸出

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

更新於: 2019-07-30

199 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

入門
廣告