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

วิธี Delete เอกสารใน MongoDB ด้วย remove() (รองรับทั้งรายการเดียวและทั้งหมด)

เพื่อลบเอกสารจากคอลเล็กชันใน MongoDB ใช้เมธอด remove() ไวยากรณ์:

db.yourCollectionName.remove(yourDeleteValue);

สร้างคอลเล็กชันตัวอย่าง


> db.deleteDocuments.insert({"UserId":1,"UserName":"Bob","UserTechnicalSubject":"Introduction to PL/SQL"});
WriteResult({ "nInserted" : 1 })
> db.deleteDocuments.insert({"UserId":2,"UserName":"Carol","UserTechnicalSubject":"Introduction to MongoDB"});
WriteResult({ "nInserted" : 1 })
> db.deleteDocuments.insert({"UserId":3,"UserName":"John","UserTechnicalSubject":"Introduction to MySQL"});
WriteResult({ "nInserted" : 1 })
> db.deleteDocuments.insert({"UserId":4,"UserName":"Maxwell","UserTechnicalSubject":"Introduction to SQL Server"});
WriteResult({ "nInserted" : 1 })

แสดงเอกสารทั้งหมด


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

ลบเอกสารเดียว (UserId: 4)


> db.deleteDocuments.remove({"UserId":4,"UserName":"Maxwell","UserTechnicalSubject":"Introduction to SQL Server"});
WriteResult({ "nRemoved" : 1 })

ตรวจสอบหลังลบ


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

เหลือเอกสาร UserId 1, 2, 3 เอกสาร UserId 4 ถูกลบแล้ว

ลบเอกสารทั้งหมด


> db.deleteDocuments.remove({});
WriteResult({ "nRemoved" : 3 })

ลบเอกสารทั้งหมดในคอลเล็กชัน deleteDocuments สำเร็จ

หมายเหตุ: remove() เป็นเมธอดเก่า (Legacy) ใน MongoDB เวอร์ชันใหม่แนะนำให้ใช้ deleteOne() และ deleteMany() แทน เพื่อความชัดเจนและควบคุมได้ดีกว่า