從陣列中返回特定欄位的 MongoDB 查詢?


若要返回特定欄位,請使用 aggregate $project。讓我們首先建立一個包含文件的集合 -

> db.returnSpecificFieldDemo.insertOne(
   {
      "StudentId":1,
      "StudentDetails": [
         {
            "StudentName":"Larry",
            "StudentAge":21,
            "StudentCountryName":"US"
         },
         {
            "StudentName":"Chris",
            "StudentAge":23,
            "StudentCountryName":"AUS"
         }
      ]
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce23d3236e8b255a5eee943")
}

以下是使用 find() 方法從集合中顯示所有文件的查詢 -

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

這將產生以下輸出 -

{
   "_id" : ObjectId("5ce23d3236e8b255a5eee943"),
   "StudentId" : 1,
   "StudentDetails" : [
      {
         "StudentName" : "Larry",
         "StudentAge" : 21,
         "StudentCountryName" : "US"
      },
      {
         "StudentName" : "Chris",
         "StudentAge" : 23,
         "StudentCountryName" : "AUS"
      }
   ]
}

以下是從陣列中返回特定欄位的查詢 -

> db.returnSpecificFieldDemo.aggregate([{$project:{_id:0, StudentId:'$StudentId', StudentCountryName:{ $arrayElemAt: ['$StudentDetails.StudentCountryName',1] }}}]);

這將產生以下輸出 -

{ "StudentId" : 1, "StudentCountryName" : "AUS" }

更新於:2019 年 7 月 30 日

608 次瀏覽

開啟你的 職業生涯

透過完成本課程獲得認證

開始學習
廣告
© . All rights reserved.