從 MongoDB 中的單個數組元素中取消設定一個屬性?


使用 $unset 運算子來取消一個屬性設定。我們首先建立一個包含文件的集合,程式碼如下:-

> db.unsetAnAttributeDemo.insertOne(
...    {
...       _id: 1,
...       "StudentDetails": [
...          {
...             "StudentFirstName": "Ramit",
...             "StudentCountryName":"UK"
...          },
...          {
...             "StudentFirstName": "Bob",
...             "StudentCountryName":"US"
...          },
...          {
...             "StudentFirstName": "Carol",
...             "StudentCountryName":"AUS"
...
...          }
...       ]
...    }
... );
{ "acknowledged" : true, "insertedId" : 1 }

以下查詢透過 find() 方法顯示集合中的所有文件,程式碼如下:-

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

這將生成以下輸出:-

{
   "_id" : 1,
   "StudentDetails" : [
      {
         "StudentFirstName" : "Ramit",
         "StudentCountryName" : "UK"
      },
      {
         "StudentFirstName" : "Bob",
         "StudentCountryName" : "US"
      },
      {
         "StudentFirstName" : "Carol",
         "StudentCountryName" : "AUS"
      }
   ]
}

以下查詢取消從一個數組元素中設定一個屬性。值為“AUS”的“StudentCountryName”屬性將被取消設定,程式碼如下:-

> db.unsetAnAttributeDemo.update({"StudentDetails.StudentCountryName": "AUS"}, {$unset:
   {"StudentDetails.$.StudentCountryName": 1}});
   WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

讓我們顯示集合中的文件,以檢查“StudentCountryName”值“AUS”的屬性是否已被清除,程式碼如下:-

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

這將生成以下輸出:-

{
   "_id" : 1,
   "StudentDetails" : [
      {
         "StudentFirstName" : "Ramit",
         "StudentCountryName" : "UK"
      },
      {
         "StudentFirstName" : "Bob",
         "StudentCountryName" : "US"
      },
      {
         "StudentFirstName" : "Carol"
      }
   ]
}

更新於: 30-07-2019

128 次瀏覽

啟動您的 職業生涯

完成課程後獲取認證

開始
廣告