Giới thiệu
Để xóa tất cả tài liệu trong một collection trừ một tài liệu cụ thể, bạn có thể sử dụng phương thức remove() kết hợp với toán tử $ne (not equal - không bằng).
Ví dụ minh họa
1. Tạo collection và thêm dữ liệu
> db.xoaTruMotTaiLieu.insertOne({"TenSinhVien":"Larry","TuoiSinhVien":21});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9c9de42d66697741252478") }
> db.xoaTruMotTaiLieu.insertOne({"TenSinhVien":"Mike","TuoiSinhVien":21,"QuocGia":"US"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9c9dea2d66697741252479") }
> db.xoaTruMotTaiLieu.insertOne({"TenSinhVien":"Chris","TuoiSinhVien":24,"QuocGia":"AUS"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9c9def2d6669774125247a") }
2. Xem tất cả tài liệu
> db.xoaTruMotTaiLieu.find().pretty();
3. Xóa tất cả trừ tài liệu có TuoiSinhVien = 24
> db.xoaTruMotTaiLieu.remove({ TuoiSinhVien: { $ne: 24 } });
WriteResult({ "nRemoved" : 2 })
4. Kiểm tra kết quả
> db.xoaTruMotTaiLieu.find().pretty();
Kết quả chỉ còn lại tài liệu của Chris:
{ "_id" : ObjectId("5c9c9def2d6669774125247a"), "TenSinhVien" : "Chris", "TuoiSinhVien" : 24, "QuocGia" : "AUS" }
Lưu ý quan trọng
- Phương thức
remove()đã bị deprecated trong các phiên bản MongoDB mới. Nên sử dụngdeleteMany()thay thế. - Cú pháp hiện đại:
db.collection.deleteMany({ TuoiSinhVien: { $ne: 24 } }) - Luôn sao lưu dữ liệu trước khi thực hiện xóa hàng loạt.