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

ลบ Item ออกจาก Array ใน MongoDB ด้วย $pull

การลบ element ออกจาก array field ใน MongoDB ใช้ operator $pull ใน update operation จะลบ ทุก element ที่ตรงเงื่อนไข

สร้างคอลเลกชันและข้อมูลตัวอย่าง

> db.demo224.insertOne({"ListOfTechnology":["Spring","Hibernate","Java"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3ee6d103d395bdc2134733") }
> db.demo224.insertOne({"ListOfTechnology":["Groovy"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3ee6ec03d395bdc2134734") }

แสดงข้อมูลก่อนลบ

> db.demo224.find();

ผลลัพธ์:

{ "_id" : ObjectId("5e3ee6d103d395bdc2134733"), "ListOfTechnology" : [ "Spring", "Hibernate", "Java" ] }
{ "_id" : ObjectId("5e3ee6ec03d395bdc2134734"), "ListOfTechnology" : [ "Groovy" ] }

Query ลบ "Java" ออกจาก Array

> db.demo224.update(
  {_id: ObjectId("5e3ee6d103d395bdc2134733")},
  {$pull: {"ListOfTechnology": "Java"}}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

คำอธิบาย:

  • Filter: {_id: ObjectId(...)} - ระบุเอกสารเป้าหมาย (แม่นยำกว่า query by array value)
  • $pull: {"ListOfTechnology": "Java"} - ลบ element ที่เท่ากับ "Java" ทุกตัวที่เจอ

ผลลัพธ์หลังลบ

> db.demo224.find();

ผลลัพธ์:

{ "_id" : ObjectId("5e3ee6d103d395bdc2134733"), "ListOfTechnology" : [ "Spring", "Hibernate" ] }
{ "_id" : ObjectId("5e3ee6ec03d395bdc2134734"), "ListOfTechnology" : [ "Groovy" ] }

Java ถูกลบออกจาก array แรก Groovy ไม่ได้รับผลกระทบ

$pull กับ Object/Array Conditions

ลบ Object ใน Array ที่ match field

db.collection.update(
  {_id: ...},
  {$pull: {items: {status: "deleted"}}}
)

ลบด้วย $in (หลายค่า)

db.demo224.update(
  {},
  {$pull: {ListOfTechnology: {$in: ["Java", "Spring"]}}},
  {multi: true}
)

ลบด้วย Condition Expression

db.collection.update(
  {},
  {$pull: {scores: {$lt: 50}}},  // ลบคะแนนต่ำกว่า 50
  {multi: true}
)

Operators ที่เกี่ยวข้องกับ Array

Positional $pull (MongoDB 5.0+) - ลบเฉพาะ index

// ลบ element index 0 ของ array items
db.collection.updateOne(
  {_id: ...},
  {$pull: {"items.0": {$exists: true}}}  // syntax ใหม่
)

สรุป: $pull = ลบตามเงื่อนไข (ทุกตัวที่ match) | $pullAll = ลบค่าที่ระบุ exact match | $pop = ลบปลาย array

Operatorคำอธิบายตัวอย่าง
$pullลบ element ที่ match condition{$pull: {tags: "old"}}
$pullAllลบหลายค่าที่ระบุ (exact match){$pullAll: {tags: ["old", "deprecated"]}}
$pushเพิ่ม element{$push: {tags: "new"}}
$addToSetเพิ่มถ้ายังไม่มี (unique){$addToSet: {tags: "unique"}}
$popลบตัวแรก/สุดท้าย{$pop: {scores: 1}} (last), -1 (first)
$shiftลบตัวแรก (alias $pop -1)