如何在查詢文件時阻止 MongoDB 返回物件 ID?


如要阻止 MongoDB 在查詢文件時返回物件 ID,你需要將_id 設為 0。我們先建立一個帶有文件的集合

> db.preventObjectIdDemo.insertOne(
...    {
...
...       "StudentName" : "Chris",
...       "StudentDetails" : [
...          {
...             "StudentTotalScore" : 540,
...             "StudentCountryName" : "US"
...          },
...          {
...             "StudentTotalScore" : 489,
...             "StudentCountryName" : "UK"
...          }
...       ]
...    }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca20a9c66324ffac2a7dc63")
}

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

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

這將產生以下輸出

{
   "_id" : ObjectId("5ca20a9c66324ffac2a7dc63"),
   "StudentName" : "Chris",
   "StudentDetails" : [
      {
         "StudentTotalScore" : 540,
         "StudentCountryName" : "US"
      },
      {
         "StudentTotalScore" : 489,
         "StudentCountryName" : "UK"
      }
   ]
}

以下是阻止 MongoDB 在查詢文件時返回物件 ID 的查詢

> db.preventObjectIdDemo.find({ _id: ObjectId("5ca20a9c66324ffac2a7dc63")},
{StudentDetails: { $slice: [0, 1] } ,'_id': 0} ).pretty();

以下是輸出,其中看不到 ObjectID

{
   "StudentName" : "Chris",
   "StudentDetails" : [
      {
         "StudentTotalScore" : 540,
         "StudentCountryName" : "US"
      }
   ]
}

更新時間: 30-7 月-2019

511 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始使用
廣告
© . All rights reserved.