透過 MongoDB 的投影從巢狀文件中移除除一個欄位外的所有欄位


將不需要包含在內的欄位設為 0。這會在使用 find() 時顯示其他值。讓我們首先建立一個帶有文件的集合 -

> db.demo237.insertOne({
...   _id:101,
...   Product: {
...      description1: {id:1001 },
...      description2: {Name:"Product-1" },
...      description3: {Price:550 }
...   }
...}
...);
{ "acknowledged" : true, "insertedId" : 101 }

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

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

這將生成以下輸出 -

{
   "_id" : 101,
   "Product" : {
      "description1" : {
         "id" : 1001
      },
      "description2" : {
         "Name" : "Product-1"
      },
      "description3" : {
         "Price" : 550
      }
   }
}

以下是透過投影從巢狀文件中移除除單一欄位外的所有欄位的查詢 -

> db.demo237.find({}, { "Product.description1": 0, "Product.description3": 0 });

這將生成以下輸出 -

{ "_id" : 101, "Product" : { "description2" : { "Name" : "Product-1" } } }

更新於: 30-Mar-2020

275 次瀏覽

開啟您的 職業生涯

透過完成本課程獲得認證

開始學習
廣告