使用 MongoD 中的陣列值獲取特定文件


使用 limi() 以及 toArray() 獲取特定的文件。toArray() 方法返回一個數組,其中包含遊標中的所有文件。我們建立一個包含文件的集合 -

> db.demo482.insertOne({_id:1,"StudentInformation":[{"Name":"Chris","Age":21}]});
{ "acknowledged" : true, "insertedId" : 1 }
> db.demo482.insertOne({_id:2,"StudentInformation":[{"Name":"Bob","Age":23}]});
{ "acknowledged" : true, "insertedId" : 2 }
> db.demo482.insertOne({_id:3,"StudentInformation":[{"Name":"David","Age":20}]});
{ "acknowledged" : true, "insertedId" : 3 }

使用 find() 方法顯示集合中的所有文件 -

> db.demo482.find();

這將產生以下輸出 -

{ "_id" : 1, "StudentInformation" : [ { "Name" : "Chris", "Age" : 21 } ] }
{ "_id" : 2, "StudentInformation" : [ { "Name" : "Bob", "Age" : 23 } ] }
{ "_id" : 3, "StudentInformation" : [ { "Name" : "David", "Age" : 20 } ] }

以下是使用 limit() 獲取特定文件的查詢 -

> db.demo482.find({}).limit(2).toArray();

這將產生以下輸出 -

[
   {
      "_id" : 1,
      "StudentInformation" : [
         {
            "Name" : "Chris",
            "Age" : 21
         }
      ]
   },
   {
      "_id" : 2,
      "StudentInformation" : [
         {
            "Name" : "Bob",
            "Age" : 23
         }
      ]
   }
]

更新於:2020 年 5 月 11 日

84 次瀏覽

開啟你的職業生涯

完成課程後獲得認證

開始學習
廣告