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

MongoDB Query สำหรับลบข้อมูลทั้งหมดใน Collection

การลบข้อมูลทั้งหมดใน Collection ของ MongoDB สามารถทำได้โดยใช้ Method remove() พร้อมเงื่อนไขว่างเปล่า {} หมายถึง Match ทุกเอกสาร เนื้อหานี้สาธิตขั้นตอนการลบข้อมูลทั้งหมด

ตัวอย่างข้อมูลทดสอบ

> db.demo309.insertOne({ "details":[ { "Name":"Chris" }, { "Name":"David" }, { "Name":"Adam" } ] } );
{ "acknowledged" : true, "insertedId" : ObjectId("5e4eb71af8647eb59e562040") }

> db.demo309.insertOne({ "details":[ { "Name":"David" }, { "Name":"Mike" }, { "Name":"Bob" } ] } );
{ "acknowledged" : true, "insertedId" : ObjectId("5e4eb7cbf8647eb59e562041") }

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

> db.demo309.find();
{
  "_id" : ObjectId("5e4eb71af8647eb59e562040"),
  "details" : [ { "Name" : "Chris" }, { "Name" : "David" }, { "Name" : "Adam" } ]
}
{
  "_id" : ObjectId("5e4eb7cbf8647eb59e562041"),
  "details" : [ { "Name" : "David" }, { "Name" : "Mike" }, { "Name" : "Bob" } ]
}

Query ลบข้อมูลทั้งหมด

> db.demo309.remove({});
WriteResult({ "nRemoved" : 2 })

ข้อควรระวังและตัวเลือกอื่น

  • remove({}) จะลบทุกเอกสารใน Collection - ใช้ด้วยความระมัดระวัง
  • ใน MongoDB 3.2+ แนะนำใช้ deleteMany({}) แทน ซึ่งชัดเจนกว่าและรองรับ Write Concern
  • หากต้องการลบ Collection ทั้งหมด (รวม Indexes) ใช้ db.collection.drop() จะเร็วกว่า
  • สำหรับ Collection ใหญ่มาก ควรพิจารณาใช้ db.collection.drop() แล้วสร้างใหม่ จะมี Performance ดีกว่า

ตัวอย่างใช้ deleteMany (แนะนำ)

> db.demo309.deleteMany({});
{ "acknowledged" : true, "deletedCount" : 2 }