本文演示如何在 MongoDB 中删除名称包含特殊字符(如双连字符 --)的集合,必须使用 db.getCollection() 方法而不能直接用点号访问。
语法
db.getCollection("yourCollectionNameWithTwoDashes").drop();
创建带双连字符的集合
> db.createCollection("company--EmployeeInformation");
{ "ok" : 1 }
插入测试数据
> db.getCollection("company--EmployeeInformation").insertOne({"CompanyName":"Amazon","EmployeeName":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd7c5ff6d78f205348bc654") }
> db.getCollection("company--EmployeeInformation").insertOne({"CompanyName":"Google","EmployeeName":"Robert"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd7c60b6d78f205348bc655") }
查看数据
> db.getCollection("company--EmployeeInformation").find();
{ "_id" : ObjectId("5cd7c5ff6d78f205348bc654"), "CompanyName" : "Amazon", "EmployeeName" : "Chris" }
{ "_id" : ObjectId("5cd7c60b6d78f205348bc655"), "CompanyName" : "Google", "EmployeeName" : "Robert" }
删除集合
> db.getCollection("company--EmployeeInformation").drop();
true
为什么需要 getCollection()?
- MongoDB Shell 中
db.collectionName语法将集合名视为 JavaScript 标识符 - 包含
-,--, 空格, 数字开头等特殊字符的名称会导致语法错误 db.getCollection("name")接受字符串参数,支持任意合法集合名称
其他需要 getCollection() 的场景
| 集合名示例 | 问题 | 解决 |
|---|---|---|
my-collection | 减号被解析为减法 | db.getCollection("my-collection") |
123numbers | 数字开头非法标识符 | db.getCollection("123numbers") |
my collection | 空格非法 | db.getCollection("my collection") |
collection@name | 特殊字符 | db.getCollection("collection@name") |
完整操作示例
// 创建
db.getCollection("my--special--collection").insertOne({x:1});
// 查询
db.getCollection("my--special--collection").find();
// 更新
db.getCollection("my--special--collection").updateOne({x:1}, {$set:{y:2}});
// 删除集合
db.getCollection("my--special--collection").drop();
// 列出所有集合(验证)
show collections;
// 或
db.getCollectionNames();
命名最佳实践
- 使用
snake_case:employee_information - 使用
camelCase:employeeInformation - 避免特殊字符、空格、保留字
- 前缀分组:
users_profiles,users_sessions