Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

วิธีลบรายการจากออบเจ็กต์ใน MongoDB


ใช้ $unset เพื่อลบฟิลด์เฉพาะในออบเจ็กต์

Operator $unset ลบฟิลด์ที่ระบุออกจากเอกสาร ใช้ dot notation ระบุพาธของฟิลด์ย่อย

ตัวอย่างข้อมูล

> db.demo467.insertOne({ _id: 101, "Information": { "Name": "Chris" } });
> db.demo467.insertOne({ _id: 102, "Information": { "Name": "David" } });

Query ลบฟิลด์ Name ใน Information ของ _id: 102

> db.demo467.update({ _id: 102 }, { $unset: { "Information.Name": 1 } }, { multi: true });
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

ผลลัพธ์

{ "_id": 101, "Information": { "Name": "Chris" } }
{ "_id": 102, "Information": { } }

คำอธิบาย

  • $unset: { "Information.Name": 1 } - ค่า 1 หมายถึง true (ลบฟิลด์นี้) ไม่ใช่ค่าที่จะตั้ง
  • dot notation รองรับความลึกได้ไม่จำกัด
  • multi: true - อัปเดตทุกเอกสารที่ match (default false ในรุ่นเก่า)

รูปแบบใหม่ (MongoDB 3.2+)

// ลบฟิลด์จากเอกสารเดียว
db.demo467.updateOne({ _id: 102 }, { $unset: { "Information.Name": "" } });

// ลบฟิลด์จากหลายเอกสาร
db.demo467.updateMany({ _id: 102 }, { $unset: { "Information.Name": "" } });

ค่าของ $unset ในรุ่นใหม่สามารถเป็นค่าอะไรก็ได้ (มักใช้ "" หรือ 1)

การลบในอาร์เรย์

หากต้องการลบอิลิเมนต์ในอาร์เรย์ ให้ใช้ $pull หรือ $pullAll แทน:

// ลบอิลิเมนต์ที่ Name = "Chris" จากอาร์เรย์ details
db.demo467.updateOne({ _id: 101 }, { $pull: { "Information.details": { Name: "Chris" } } });