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

Xóa collection có ký tự đặc biệt trong MongoDB (dùng getCollection)

Khi tên collection chứa ký tự đặc biệt (dấu gạch dưới _, gạch ngang -, dấu chấm ., khoảng trắng...), bạn **không thể** truy cập trực tiếp bằng db.tênCollection. Phải dùng db.getCollection("tênCollection").

Cú pháp

// Tham chiếu collection
db.getCollection("tên-collection-hoặc_tên")

// Xóa collection
db.getCollection("tên-collection-hoặc_tên").drop();

Ví dụ minh họa

Tạo collection tên _personalInformation (bắt đầu bằng gạch dưới):

> db.createCollection("_personalInformation");
{ "ok" : 1 }
> db.getCollection('_personalInformation').insertOne({ "ClientName": "Chris", "ClientCountryName": "US" });
> db.getCollection('_personalInformation').insertOne({ "ClientName": "Mike", "ClientCountryName": "UK" });
> db.getCollection('_personalInformation').insertOne({ "ClientName": "David", "ClientCountryName": "AUS" });

Hiển thị dữ liệu:

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

Kết quả:

{ "_id" : ..., "ClientName" : "Chris", "ClientCountryName" : "US" }
{ "_id" : ..., "ClientName" : "Mike", "ClientCountryName" : "UK" }
{ "_id" : ..., "ClientName" : "David", "ClientCountryName" : "AUS" }

Xóa collection

> db.getCollection("_personalInformation").drop();

Kết quả:

true

true xác nhận collection đã bị xóa hoàn toàn.

Các thao tác khác với getCollection()

Mọi thao tác CRUD, index, aggregation... đều dùng chung cú pháp:

var coll = db.getCollection("my-collection.name");
coll.find({});
coll.insertOne({...});
coll.createIndex({ "field": 1 });
coll.aggregate([...]);
coll.dropIndex("field_1");

Lưu ý

  • Tên collection **không được** chứa ký tự $, \0 (null), hoặc rỗng.
  • Không nên đặt tên bắt đầu bằng system. (dành cho hệ thống).
  • Trong driver (Node.js, Python...): db.collection("tên-collection") hoặc db["tên-collection"].
  • Liệt kê tất cả collection: db.getCollectionNames() hoặc show collections.