蓝色天空.知识 · 实践 · 创造
我的收藏
MongoDB 教程目录 49章
MongoDB / LEARN BY DOING

MongoDB 更新集合名

详解通过 adminCommand({ renameCollection, to, dropTarget }) 同库与跨库重命名集合的语法、权限要求、冲突处理与数据索引保留机制。

学完这一章,你能够

  • 详解通过 adminCommand({ renameCollection, to, dropTarget }) 同库与跨库重命名集合的语法、权限要求、冲突处理与数据索引保留机制。

renameCollection 命令语法与参数说明

MongoDB 无法通过普通修改属性的方式改集合名,而是借助在 `admin` 数据库上下文中执行的 `renameCollection` 管理命令完成(Shell 中也提供同库便捷包装方法 `db.<col>.renameCollection("newName")`,底层仍调用同名命令)。完整管理命令格式为 `db.adminCommand({ renameCollection: "sourceDb.sourceCollection", to: "targetDb.targetCollection", dropTarget: <boolean> })`:其中 `renameCollection` 为源集合全限定命名空间,`to` 为目标全限定命名空间,可选布尔值 `dropTarget`(默认 `false`)决定目标集合已存在时是否先删除覆盖。

同库与跨库重命名实操

执行同库重命名(如将 `test.oldCollection` 改为 `test.newCollection`)时,先切至 `test` 库(或在任意库调用 `db.adminCommand(...)`)并传入同库源与目标命名空间即可;若需把集合迁移到另一数据库(例如由 `test.oldCollection` 移至 `production.newCollection`),直接将 `to` 的数据库前缀改为 `production` 即可(注意分片集合跨库重命名存在架构限制,且跨库移动需要锁与元数据迁移,大集合需评估维护窗口)。

权限、冲突检查与失败恢复

重命名集合须重点关注三项约束:第一,操作者必须同时具备源库与目标库的管理权限(通常要求 `dbAdmin` 或 `dbOwner` 角色,普通 `readWrite` 会被拒绝);第二,默认 `dropTarget: false` 时目标集合不得已存在,否则命令直接报错;第三,重命名成功后原集合内全部文档与二级索引均会完整保留。操作完成后可执行 `use test` 与 `show collections` 核验新集合名;若因目标已存在而报错,可确认无用后先切至目标库执行 `db.newCollection.drop()` 再重跑 `renameCollection`(或在确认覆盖语义后显式设置 `dropTarget: true`)。

运行同库/跨库 renameCollection、目标冲突与 dropTarget 覆盖及 dbAdmin 权限校验

含完整源码 · 155 行
展开查看收起
python
"""Offline MongoDB adminCommand renameCollection, cross-DB move & RBAC verifier (Ch14 renamecollection)."""
import json

VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"


class OfflineRenameServer:
    def __init__(self):
        self.dbs = {
            "test": {
                "oldCollection": {
                    "docs": [{"_id": 1, "name": "alpha"}, {"_id": 2, "name": "beta"}],
                    "indexes": ["_id_", "name_1"],
                }
            },
            "production": {
                "existingTarget": {
                    "docs": [{"_id": 99, "name": "legacy"}],
                    "indexes": ["_id_"],
                }
            },
        }
        self.user_roles = {
            "admin_user": {("test", "dbAdmin"), ("production", "dbOwner")},
            "app_rw_user": {("test", "readWrite"), ("production", "readWrite")},
        }

    def has_rename_perm(self, user: str, src_db: str, dst_db: str) -> bool:
        roles = self.user_roles.get(user, set())
        ok_src = any(db == src_db and r in ("dbAdmin", "dbOwner") for db, r in roles)
        ok_dst = any(db == dst_db and r in ("dbAdmin", "dbOwner") for db, r in roles)
        return ok_src and ok_dst

    def admin_rename_collection(self, user: str, src_ns: str, dst_ns: str, drop_target: bool = False):
        src_db, src_col = src_ns.split(".", 1)
        dst_db, dst_col = dst_ns.split(".", 1)
        if not self.has_rename_perm(user, src_db, dst_db):
            return {"ok": 0, "errmsg": "Unauthorized: requires dbAdmin or dbOwner"}
        if src_col not in self.dbs.get(src_db, {}):
            return {"ok": 0, "errmsg": "Source namespace does not exist"}
        dst_bucket = self.dbs.setdefault(dst_db, {})
        if dst_col in dst_bucket:
            if not drop_target:
                return {"ok": 0, "errmsg": "target namespace exists"}
            del dst_bucket[dst_col]
        dst_bucket[dst_col] = self.dbs[src_db].pop(src_col)
        return {"ok": 1}


def case_same_db_rename_collection():
    srv = OfflineRenameServer()
    res = srv.admin_rename_collection("admin_user", "test.oldCollection", "test.newCollection")
    cols = sorted(srv.dbs["test"].keys())
    moved = srv.dbs["test"]["newCollection"]
    actual = {
        "ok": res["ok"],
        "test_collections": cols,
        "preserved_doc_count": len(moved["docs"]),
        "preserved_indexes": moved["indexes"],
    }
    expected = {
        "ok": 1,
        "test_collections": ["newCollection"],
        "preserved_doc_count": 2,
        "preserved_indexes": ["_id_", "name_1"],
    }
    return {
        "name": "same_db_rename_collection",
        "summary": "验证同库重命名 test.oldCollection -> test.newCollection 完整保留文档与索引。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_cross_db_rename_collection():
    srv = OfflineRenameServer()
    res = srv.admin_rename_collection("admin_user", "test.oldCollection", "production.newCollection")
    actual = {
        "ok": res["ok"],
        "test_collections": sorted(srv.dbs["test"].keys()),
        "prod_collections": sorted(srv.dbs["production"].keys()),
        "moved_indexes": srv.dbs["production"]["newCollection"]["indexes"],
    }
    expected = {
        "ok": 1,
        "test_collections": [],
        "prod_collections": ["existingTarget", "newCollection"],
        "moved_indexes": ["_id_", "name_1"],
    }
    return {
        "name": "cross_db_rename_collection",
        "summary": "验证跨库重命名 test.oldCollection -> production.newCollection 迁移集合文档与索引。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_target_conflict_and_drop_target():
    srv = OfflineRenameServer()
    conflict = srv.admin_rename_collection("admin_user", "test.oldCollection", "production.existingTarget", drop_target=False)
    override = srv.admin_rename_collection("admin_user", "test.oldCollection", "production.existingTarget", drop_target=True)
    actual = {
        "conflict_ok": conflict["ok"],
        "conflict_msg": conflict["errmsg"],
        "override_ok": override["ok"],
        "new_target_doc_ids": [d["_id"] for d in srv.dbs["production"]["existingTarget"]["docs"]],
    }
    expected = {
        "conflict_ok": 0,
        "conflict_msg": "target namespace exists",
        "override_ok": 1,
        "new_target_doc_ids": [1, 2],
    }
    return {
        "name": "target_conflict_and_drop_target",
        "summary": "验证目标集合已存在时默认 dropTarget:false 报错,设为 true 后覆盖目标集合。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_rename_rbac_permission_check():
    srv = OfflineRenameServer()
    denied = srv.admin_rename_collection("app_rw_user", "test.oldCollection", "test.newCollection")
    allowed = srv.admin_rename_collection("admin_user", "test.oldCollection", "test.newCollection")
    actual = {
        "rw_user_denied": denied["ok"] == 0,
        "admin_user_allowed": allowed["ok"] == 1,
    }
    expected = {"rw_user_denied": True, "admin_user_allowed": True}
    return {
        "name": "rename_rbac_permission_check",
        "summary": "验证执行 renameCollection 需具备 dbAdmin/dbOwner 权限,普通 readWrite 用户被拒绝。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_same_db_rename_collection(),
        case_cross_db_rename_collection(),
        case_target_conflict_and_drop_target(),
        case_rename_rbac_permission_check(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
验证同库与跨库迁移保留全部文档和索引、目标冲突拦截、dropTarget:true 覆盖及 readWrite 越权拒绝。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1732.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:MongoDB

课程关联工程包(登记关联49章) · 含当前章节或实例 · mbskycom202612a1732.zip

下载课程关联工程包:MongoDB

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1767.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

不需要;`renameCollection` 会完整保留集合内的全部文档及已有索引元数据。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习