如何從 MongoDB 集合中讀取特定的鍵值對?


您可以使用 dot(.) 符號來讀取 MongoDB 集合中某個特定的鍵值對。我們首先建立一個帶有文件的集合 -

> db.readSpecificKeyValueDemo.insertOne(
...    {
...       "_id": 100,
...       "StudentDetails":
...       {
...          "StudentFirstName" : "David",
...          "StudentLastName" :"Miller",
...          "StudentAge":23,
...          "StudentCountryName":"US"
...       }
...    }
... );
{ "acknowledged" : true, "insertedId" : 100 }

以下查詢可藉助 find() 方法顯示集合中的所有文件 -

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

這會產生以下輸出 -

{
   "_id" : 100,
   "StudentDetails" : {
      "StudentFirstName" : "David",
      "StudentLastName" : "Miller",
      "StudentAge" : 23,
      "StudentCountryName" : "US"
   }
}

以下查詢可從 MongoDB 集合中讀取某個特定的鍵值對 -

> db.readSpecificKeyValueDemo.find({},{"StudentDetails.StudentCountryName":1}).pretty();

這會產生以下輸出 -

{ "_id" : 100, "StudentDetails" : { "StudentCountryName" : "US" } }

更新於:2019 年 7 月 30 日

807 次瀏覽

開啟您的 事業

完成課程獲得認證

開始吧
廣告
© . All rights reserved.