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

Cách xóa collection số (numeric collection) trong MongoDB?

Collection có tên là số (numeric collection name) không thể truy cập trực tiếp bằng ký pháp dấu chấm (db.2536464 sẽ gây lỗi cú pháp). Bạn phải sử dụng db.getCollection().

Cú pháp xóa

db.getCollection("tênCollectionSố").drop();

Ví dụ thực hành

Tạo collection tên "2536464":

> db.createCollection("2536464");
{ "ok" : 1 }

Chèn document:

> db.getCollection("2536464").insertOne({"Record":1});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca254a46304881c5ce84b8e") }
> db.getCollection("2536464").insertOne({"Record":2});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca254a76304881c5ce84b8f") }
> db.getCollection("2536464").insertOne({"Record":3});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca254a96304881c5ce84b90") }

Hiển thị document:

> db.getCollection("2536464").find().pretty();

Xóa collection

> db.getCollection("2536464").drop();
true

Lưu ý: Phương thức getCollection() bắt buộc khi tên collection:

  • Là số (bắt đầu bằng chữ số)
  • Chứa khoảng trắng hoặc ký tự đặc biệt
  • Trùng với từ khóa/method shell (group, version, v.v.)
Đây là cách chuẩn để tham chiếu collection theo tên chuỗi trong MongoDB shell.