Bài 13: MongoDB - Xoá Document - MongoDB

Đăng bởi: Admin | Lượt xem: 1413 | Chuyên mục: SQL


1. Phương thức remove() 

Phương thức remove() trong MongoDB được sử dụng để xóa Document từ Collection. Phương thức remove() nhận hai tham số. Tham số đầu tiên deletion criteria xác định Document để xóa, và tham số thứ hai là justOne.
  1. deletion criteria: (Tùy ý) Xác định Document để xóa.
  2. justOne: (Tùy ý) Nếu được thiết lập là true hoặc 1, thì chỉ xóa một Document.
Cú pháp
Cú pháp cơ bản của phương thức remove() là như sau:
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
Ví dụ
Bạn theo dõi Collection có tên mycol có dữ liệu sau:
{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},
{_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}
Ví dụ sau sẽ xóa tất cả Document có title là 'MongoDB Overview':
>db.mycol.remove({'title':'MongoDB Overview'})
WriteResult({"nRemoved" : 1})
> db.mycol.find()
{"_id" : ObjectId("507f191e810c19729de860e2"), "title" : "NoSQL Overview" }
{"_id" : ObjectId("507f191e810c19729de860e3"), "title" : "Tutorials Point Overview" }

2. Chỉ xóa một Document

Nếu có nhiều bản ghi và bạn chỉ muốn xóa bản ghi đầu tiên, thì thiết lập tham số justOne trong phương thức remove().
>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

3. Xóa tất cả Document

Nếu bạn không xác định deletion criteria, thì MongoDB sẽ xóa toàn bộ Document từ Collection. Điều này tương đương với lệnh truncate trong SQL.
>db.mycol.remove() >db.mycol.find() >
Bài tiếp theo: MongoDB - Projection >>
vncoder logo

Theo dõi VnCoder trên Facebook, để cập nhật những bài viết, tin tức và khoá học mới nhất!