Để xóa chính xác một tài liệu, sử dụng deleteOne() (MongoDB 3.2+) hoặc remove({query}, {justOne: true}) (cũ). Truyền bộ lọc khớp duy nhất một tài liệu (thường là _id hoặc trường unique).
Dữ liệu mẫu
> db.demo165.insertOne({"ClientId":101,"ClientName":"Chris","ClientAge":34});
{ "acknowledged" : true, "insertedId" : ObjectId("5e36895c9e4f06af551997cc") }
> db.demo165.insertOne({"ClientId":102,"ClientName":"Bob","ClientAge":32});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3689659e4f06af551997cd") }
> db.demo165.insertOne({"ClientId":103,"ClientName":"David","ClientAge":35});
{ "acknowledged" : true, "insertedId" : ObjectId("5e36896d9e4f06af551997ce") }
Xem dữ liệu
> db.demo165.find();
{ "_id" : ObjectId("5e36895c9e4f06af551997cc"), "ClientId" : 101, "ClientName" : "Chris", "ClientAge" : 34 }
{ "_id" : ObjectId("5e3689659e4f06af551997cd"), "ClientId" : 102, "ClientName" : "Bob", "ClientAge" : 32 }
{ "_id" : ObjectId("5e36896d9e4f06af551997ce"), "ClientId" : 103, "ClientName" : "David", "ClientAge" : 35 }
Xóa tài liệu ClientId=102
> db.demo165.remove({"ClientId":102});
WriteResult({ "nRemoved" : 1 })
Kết quả
> db.demo165.find();
{ "_id" : ObjectId("5e36895c9e4f06af551997cc"), "ClientId" : 101, "ClientName" : "Chris", "ClientAge" : 34 }
{ "_id" : ObjectId("5e36896d9e4f06af551997ce"), "ClientId" : 103, "ClientName" : "David", "ClientAge" : 35 }
Khuyến nghị: Dùng db.demo165.deleteOne({"ClientId":102}) – cú pháp hiện đại, rõ ràng hơn. remove() không có tùy chọn justOne trong một số driver mới. Luôn ưu tiên xóa bằng _id để đảm bảo chính xác tuyệt đối.