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

Cách hiệu quả xóa tất cả bản ghi trong MongoDB: drop() vs remove()

Nếu bạn dùng phương thức drop(), nó sẽ xóa toàn bộ thông tin về collection (kể cả index). Ngược lại, remove() chỉ xóa các bản ghi nhưng giữ lại collection và các index.

Sử dụng drop()

Tạo collection với document và index:

> db.dropWorkingDemo.createIndex({"FirstName":1});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
> db.dropWorkingDemo.insertOne({"FirstName":"John"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cdd8742bf3115999ed511e9") }

Hiển thị document:

> db.dropWorkingDemo.find();

Kết quả:

{ "_id" : ObjectId("5cdd8742bf3115999ed511e9"), "FirstName" : "John" }

Thực hiện drop():

> db.dropWorkingDemo.drop();

Kết quả:

true

Kiểm tra index sau drop():

> db.dropWorkingDemo.getIndexes();

Kết quả (không còn index):

[ ]

Sử dụng remove()

Tạo collection mới với index:

> db.removeDemo.createIndex({"FirstName":1});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
> db.removeDemo.insertOne({"FirstName":"John"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cdd8868bf3115999ed511ea") }

Hiển thị document:

> db.removeDemo.find();

Kết quả:

{ "_id" : ObjectId("5cdd8868bf3115999ed511ea"), "FirstName" : "John" }

Thực hiện remove():

> db.removeDemo.remove({});
WriteResult({ "nRemoved" : 1 })

Kiểm tra index sau remove():

> db.removeDemo.getIndexes();

Kết quả (index vẫn còn):

[
  { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.removeDemo" },
  { "v" : 2, "key" : { "FirstName" : 1 }, "name" : "FirstName_1", "ns" : "test.removeDemo" }
]

Kết luận: remove() giữ lại index, drop() xóa cả index.