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

วิธีลบเอกสารทั้งหมดยกเว้นเอกสารเดียวใน MongoDB

การลบเอกสารทั้งหมดยกเว้นเอกสารที่ต้องการใน MongoDB

เพื่อลบเอกสารทั้งหมดในคอลเลกชันยกเว้นเอกสารที่ตรงตามเงื่อนไขที่กำหนด ใช้เมธอด remove() ร่วมกับออเปอเรเตอร์ $ne (not equal)

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

> db.removeAllDocumentsExceptOneDemo.insertOne({"StudentName":"Larry","StudentAge":21});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9c9de42d66697741252478") }
> db.removeAllDocumentsExceptOneDemo.insertOne({"StudentName":"Mike","StudentAge":21,"StudentCountryName":"US"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9c9dea2d66697741252479") }
> db.removeAllDocumentsExceptOneDemo.insertOne({"StudentName":"Chris","StudentAge":24,"StudentCountryName":"AUS"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9c9def2d6669774125247a") }

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

> db.removeAllDocumentsExceptOneDemo.find().pretty();

ผลลัพธ์:

{ "_id" : ObjectId("5c9c9de42d66697741252478"), "StudentName" : "Larry", "StudentAge" : 21 }
{ "_id" : ObjectId("5c9c9dea2d66697741252479"), "StudentName" : "Mike", "StudentAge" : 21, "StudentCountryName" : "US" }
{ "_id" : ObjectId("5c9c9def2d6669774125247a"), "StudentName" : "Chris", "StudentAge" : 24, "StudentCountryName" : "AUS" }

คำสั่งลบเอกสารที่ไม่ตรงเงื่อนไข (เก็บเอกสารที่ StudentAge = 24)

> db.removeAllDocumentsExceptOneDemo.remove({ StudentAge: { $ne: 24 } });
WriteResult({ "nRemoved" : 2 })

ตรวจสอบข้อมูลหลังลบ

> db.removeAllDocumentsExceptOneDemo.find().pretty();

ผลลัพธ์ (เหลือเพียงเอกสารที่ StudentAge = 24):

{ "_id" : ObjectId("5c9c9def2d6669774125247a"), "StudentName" : "Chris", "StudentAge" : 24, "StudentCountryName" : "AUS" }

คำอธิบาย

  • $ne : ออเปอเรเตอร์ "ไม่เท่ากับ" - จะเลือกเอกสารที่ค่าของฟิลด์ไม่เท่ากับค่าที่ระบุ
  • remove() : ลบเอกสารที่ตรงตามเงื่อนไข (ใน MongoDB เวอร์ชันใหม่แนะนำให้ใช้ deleteMany() แทน)
  • nRemoved : แสดงจำนวนเอกสารที่ถูกลบ

หมายเหตุ: ตั้งแต่ MongoDB 3.2+ ควรใช้ deleteMany({ StudentAge: { $ne: 24 } }) แทน remove() เพื่อความชัดเจนและความปลอดภัยมากขึ้น