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

ดึง (Pull) ทุก Element ออกจากอาร์เรย์ใน MongoDB โดยไม่มีเงื่อนไข

ใช้ $set ตั้งค่าอาร์เรย์เป็น Empty Array []

เมื่อต้องการลบ ทุกสมาชิก ในอาร์เรย์ (Clear Array) วิธีง่ายและเร็วที่สุดคือใช้ $set ตั้งค่าเป็น [] แทนการใช้ $pull ซ้ำๆ

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

> db.pullAllElementDemo.insertOne({
    "StudentId": 101,
    "StudentDetails": [
        { "StudentName": "Carol", "StudentAge": 21, "StudentCountryName": "US" },
        { "StudentName": "Chris", "StudentAge": 24, "StudentCountryName": "AUS" }
    ]
});
> db.pullAllElementDemo.insertOne({
    "StudentId": 102,
    "StudentDetails": [
        { "StudentName": "Robert", "StudentAge": 27, "StudentCountryName": "UK" },
        { "StudentName": "David", "StudentAge": 23, "StudentCountryName": "US" }
    ]
});

คำสั่ง Clear Array ของ StudentId 102

> db.pullAllElementDemo.update(
    { StudentId: 102 },
    { "$set": { "StudentDetails": [] } }
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

ผลลัพธ์: StudentDetails ของ 102 กลายเป็น []

> db.pullAllElementDemo.find().pretty();
{ "StudentId" : 101, "StudentDetails" : [ { "StudentName" : "Carol", ... }, { "StudentName" : "Chris", ... } ] }
{ "StudentId" : 102, "StudentDetails" : [ ] }

วิธีอื่นๆ และการเปรียบเทียบ

วิธีคำสั่งเหมาะสำหรับAtomic
$set: { arr: [] }Clear ทั้งอาร์เรย์ลบทั้งหมด (Fastest)✅
$pull: { arr: { $exists: true } }Pull ทุก Elementลบทั้งหมด (ช้ากว่า)✅
$unset: { arr: 1 }ลบ Field ทิ้งลบ Field เลย (ไม่ใช่ Clear)✅
$pop: { arr: 1 } (รันหลายครั้ง)Pop ทีละตัวลบทีละตัว (Slow)✅

ข้อควรระวัง

  • $set: { arr: [] } แทนที่อาร์เรย์ทั้งหมด - Reference เก่าจะหาย
  • หากอาร์เรย์ใหญ่มาก อาจมีผลต่อ Performance (แต่เร็วกว่า $pull หลายรอบ)
  • ใช้ updateMany({}, { $set: { arr: [] } }) เพื่อ Clear ทุก Document

ใช้ $pull เมื่อไหร่?

  • ลบ เฉพาะบาง Element ตามเงื่อนไข
  • ลบ Element ที่ Match Object Pattern
  • ต้องการ Atomic Remove โดยไม่แทนที่ Array ทั้งหมด