Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Xóa tài liệu theo _id trong MongoDB

Để xóa tài liệu theo _id, sử dụng phương thức remove() (hoặc deleteOne()/deleteMany() trong phiên bản mới). Cú pháp:

db.yourCollectionName.remove({_id:yourObjectId});

Tạo collection mẫu:

> db.demo518.insertOne({"ClientName":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e88b02db3fbf26334ef610e") }
> db.demo518.insertOne({"ClientName":"Bob"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e88b030b3fbf26334ef610f") }
> db.demo518.insertOne({"ClientName":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e88b035b3fbf26334ef6110") }

Hiển thị dữ liệu:

> db.demo518.find();

Kết quả:

Xóa tài liệu có _id cụ thể:

> db.demo518.remove({_id:ObjectId("5e88b02db3fbf26334ef610e")});
WriteResult({ "nRemoved" : 1 })

Kiểm tra lại - tài liệu Chris đã bị xóa:

> db.demo518.find();

Kết quả:

Khuyến nghị: Từ MongoDB 3.2+, nên dùng deleteOne() hoặc deleteMany() thay vì remove():

db.demo518.deleteOne({_id: ObjectId("...")})

Phương thức mới trả về đối tượng kết quả chi tiết hơn (acknowledged, deletedCount).