Để xóa tài liệu từ collection, dùng phương thức remove(). Cú pháp:
db.yourCollectionName.remove(yourDeleteValue);
Tạo collection với tài liệu:
>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 })
Hiển thị tất cả:
> db.deleteDocuments.find().pretty();
Xóa một tài liệu đơn lẻ
Xóa tài liệu UserId = 4:
>db.deleteDocuments.remove({"UserId":4,"UserName":"Maxwell","UserTechnicalSubject":"Introduction to SQL Server"});
WriteResult({ "nRemoved" : 1 })
Kiểm tra lại:
> db.deleteDocuments.find().pretty();
Kết quả (UserId 4 đã bị xóa):
{ "_id" : ObjectId("5c6aaa9e64f3d70fcc9147ff"), "UserId" : 1, "UserName" : "Bob", "UserTechnicalSubject" : "Introduction to PL/SQL" }
{ "_id" : ObjectId("5c6aaab464f3d70fcc914800"), "UserId" : 2, "UserName" : "Carol", "UserTechnicalSubject" : "Introduction to MongoDB" }
{ "_id" : ObjectId("5c6aaac764f3d70fcc914801"), "UserId" : 3, "UserName" : "John", "UserTechnicalSubject" : "Introduction to MySQL" }
Xóa tất cả tài liệu
Cú pháp:
db.yourCollectionName.remove({ });
Thực thi:
> db.deleteDocuments.remove({});
WriteResult({ "nRemoved" : 3 })
Tất cả tài liệu trong collection deleteDocuments đã bị xóa.