MongoDB 更新集合名

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(同库)dbAdminreadWrite + find
renameCollection(跨库)dbAdminAnyDatabaseroot
// 创建有权限的用户
use admin
db.createUser({
  user: "dba",
  pwd: "DBA2025!",
  roles: ["dbAdminAnyDatabase"]
})

六、常见问题与解决方案

问题原因解决方案
not authorized权限不足使用 rootdbAdmin 用户
target namespace exists目标集合已存在dropTarget: true 或先删除
collection not found源集合不存在检查 show collections
索引丢失重命名不复制索引自动保留,无需担心

七、GUI 工具重命名

工具操作步骤
MongoDB Compass集合 → 右键 → Rename Collection → 输入新名
VS Code + MongoDB集合节点 → 右键 → Rename Collection
MongoDB AtlasCollections → 集合名 → 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 批量重命名,欢迎继续提问!

文章已创建 2349

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部