ใช้ตัวดำเนินการ $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"
}
]
} ต่อไปนี้เป็นแบบสอบถามเพื่อยกเลิกการตั้งค่าแอตทริบิวต์จากองค์ประกอบอาร์เรย์เดียว แอตทริบิวต์ “StudentCountryName” ที่มีค่า “AUS” จะยกเลิกการตั้งค่า -
> 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"
}
]
}