MongoDB 8.0+**
更新集合名 = renameCollection()
操作不可逆,建议先备份!
一、核心命令:db.collection.renameCollection()
db.oldName.renameCollection("newName")
成功返回:
{ ok: 1 }
失败返回:{ ok: 0, errmsg: "..." }
二、完整操作流程(推荐)
graph TD
A[1. 确认集合存在] --> B[2. 备份数据]
B --> C[3. 执行重命名]
C --> D[4. 验证成功]
D --> E[5. 更新应用代码]
三、完整示例
// 1. 连接数据库
mongosh -u admin -p --authenticationDatabase admin
// 2. 切换到目标数据库
use company
// 3. 确认集合存在
show collections
// 输出:staff, depts, proj
// 4. 备份集合(推荐)
mongodump --db=company --collection=staff --out=/backup/staff_$(date +%Y%m%d)
// 5. 重命名集合
db.staff.renameCollection("employees")
// 6. 验证
show collections
// 输出:employees, depts, proj
db.employees.findOne().pretty()
四、跨数据库重命名(高级)
// 将 company.staff 重命名为 hr.employees
db.getSiblingDB('company').staff.renameCollection(
"employees",
true, // dropTarget: true → 如果目标存在则覆盖
{ db: "hr" } // 目标数据库
)
五、权限要求
| 操作 | 所需角色 |
|---|---|
renameCollection(同库) | dbAdmin 或 readWrite + find |
renameCollection(跨库) | dbAdminAnyDatabase 或 root |
// 创建有权限的用户
use admin
db.createUser({
user: "dba",
pwd: "DBA2025!",
roles: ["dbAdminAnyDatabase"]
})
六、常见问题与解决方案
| 问题 | 原因 | 解决方案 |
|---|---|---|
not authorized | 权限不足 | 使用 root 或 dbAdmin 用户 |
target namespace exists | 目标集合已存在 | 加 dropTarget: true 或先删除 |
collection not found | 源集合不存在 | 检查 show collections |
| 索引丢失 | 重命名不复制索引 | 自动保留,无需担心 |
七、GUI 工具重命名
| 工具 | 操作步骤 |
|---|---|
| MongoDB Compass | 集合 → 右键 → Rename Collection → 输入新名 |
| VS Code + MongoDB | 集合节点 → 右键 → Rename Collection |
| MongoDB Atlas | Collections → 集合名 → Rename |
八、批量重命名脚本
// rename_collections.js
const dbName = "ecommerce";
const renames = [
{ old: "product", new: "products" },
{ old: "order", new: "orders" },
{ old: "cust", new: "customers" }
];
use dbName;
renames.forEach(pair => {
const oldCol = pair.old;
const newCol = pair.new;
if (db.getCollectionNames().includes(oldCol)) {
print(`重命名 ${oldCol} → ${newCol}`);
const result = db[oldCol].renameCollection(newCol, true);
printjson(result);
} else {
print(`跳过:集合 ${oldCol} 不存在`);
}
});
print("批量重命名完成!");
show collections;
运行:
mongosh rename_collections.js
九、注意事项(生产必读)
| 注意 | 说明 |
|---|---|
| 备份 | mongodump 是保险 |
| 应用代码 | 重命名后需同步更新所有查询 |
| 索引/验证规则 | 自动保留 |
| 视图(View) | 重命名不影响视图 |
| GridFS | 不能重命名 fs.files / fs.chunks |
十、一句话总结
**“MongoDB 更新集合名 =
db.old.renameCollection('new')+ **先备份”
快速命令模板
// 推荐:安全重命名
mongodump --db=myapp --collection=users --out=/backup && \
mongosh -eval "use myapp; db.users.renameCollection('customers')"
// 强制覆盖目标
db.old.renameCollection("new", true)
官方文档:
https://www.mongodb.com/docs/manual/reference/method/db.collection.renameCollection/
如需 自动同步应用代码、重命名后更新索引、从 SQL 迁移表名规范 或 Atlas 批量重命名,欢迎继续提问!