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

Cách xóa collection MongoDB tên 'group'?

group là tên phương thức (method) có sẵn trong MongoDB shell, do đó không thể truy cập trực tiếp như collection thông thường (db.group sẽ tham chiếu đến method, không phải collection). Để thao tác với collection tên "group", bạn phải sử dụng db.getCollection('group').

Tạo collection tên 'group'

> db.createCollection('group');
{ "ok" : 1 }
> db.getCollection('group').insertOne({"StudentName":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb80fe9623186894665ae3c") }
> db.getCollection('group').insertOne({"StudentName":"Robert"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb80fef623186894665ae3d") }

Hiển thị document:

> db.getCollection('group').find().pretty();

Xóa collection 'group'

> db.getCollection('group').drop();
true

Lưu ý quan trọng:

  • Luôn dùng db.getCollection('tênCollection') khi tên collection trùng với từ khóa hoặc phương thức shell (group, version, help, v.v.)
  • Cũng áp dụng cho tên collection có ký tự đặc biệt, khoảng trắng, hoặc bắt đầu bằng số
  • drop() xóa hoàn toàn collection và tất cả dữ liệu bên trong

Đây là pattern chung để làm việc với các collection có tên "đặc biệt" trong MongoDB.