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

MongoDB 删除数据库

讲解 MongoDB 使用 db.dropDatabase() 删除当前数据库的语法、安全确认流程、返回结果,以及搭配 db.collection.drop() 删除单个集合的方法。

学完这一章,你能够

  • 讲解 MongoDB 使用 db.dropDatabase() 删除当前数据库的语法、安全确认流程、返回结果,以及搭配 db.collection.drop() 删除单个集合的方法。

db.dropDatabase() 语法与安全删除流程

在 MongoDB 中删除整个数据库使用 `db.dropDatabase()` 方法,它会移除当前激活数据库及其下属全部集合与索引。由于默认激活库为 `test`,执行该不可逆操作前务必先运行 `db` 确认当前所处数据库,避免误删生产数据。

标准删除流程分为四步:首先执行 `show dbs` 核实目标库(如 `demo_db`)存在;接着执行 `use demo_db` 切换至目标库;随后运行 `db.dropDatabase()`,成功时服务端返回 `{ "dropped": "demo_db", "ok": 1 }`;最后再次执行 `show dbs` 确认目标库已从列表中消失,而 `admin`、`config`、`local` 等系统库保持完好。

仅删除单个集合:db.collection.drop()

若只需移除某个库中的单张集合而非整库销毁,应使用 `db.<collection>.drop()` 方法。先以 `use` 切入目标库并用 `show collections`(或其别名 `show tables`)核对集合名,调用 `db.site.drop()` 成功删除后返回 `true`(若集合原本不存在则返回 `false`),再次查看集合列表即可确认移除完成。

运行 db.dropDatabase() 全流程、默认 test 库删除、collection.drop() 及空库幂等删除验证

含完整源码 · 150 行
展开查看收起
python
"""Offline MongoDB dropDatabase() & collection.drop() verifier (Ch12 dropdatabase)."""
import json

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


class MiniMongoDropStore:
    def __init__(self):
        self.dbs = {
            "admin": {"system.version": [{}]},
            "config": {"system.sessions": [{}]},
            "local": {"startup_log": [{}]},
            "demo_db": {"site": [{"name": "蓝色天空网"}], "logs": [{"msg": "init"}]},
            "test": {"scratch": [{"v": 1}]},
        }
        self.current_db = "test"

    def show_dbs(self):
        return sorted(db for db, cols in self.dbs.items() if cols)

    def use(self, name: str):
        self.current_db = name

    def show_collections(self):
        return sorted(self.dbs.get(self.current_db, {}).keys())

    def create_collection(self, col: str):
        self.dbs.setdefault(self.current_db, {}).setdefault(col, [])

    def drop_database(self):
        if self.current_db in self.dbs:
            del self.dbs[self.current_db]
            return {"dropped": self.current_db, "ok": 1}
        return {"ok": 1}

    def drop_collection(self, col: str) -> bool:
        db_cols = self.dbs.get(self.current_db, {})
        if col in db_cols:
            del db_cols[col]
            return True
        return False


def case_drop_database_workflow():
    st = MiniMongoDropStore()
    before = st.show_dbs()
    st.use("demo_db")
    res = st.drop_database()
    after = st.show_dbs()
    actual = {
        "before_has_demo_db": "demo_db" in before,
        "drop_response": res,
        "after_has_demo_db": "demo_db" in after,
        "system_dbs_intact": all(k in after for k in ("admin", "config", "local")),
    }
    expected = {
        "before_has_demo_db": True,
        "drop_response": {"dropped": "demo_db", "ok": 1},
        "after_has_demo_db": False,
        "system_dbs_intact": True,
    }
    return {
        "name": "drop_database_workflow",
        "summary": "验证 show dbs -> use demo_db -> db.dropDatabase() -> show dbs 全流程及返回值。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_drop_default_test_database():
    st = MiniMongoDropStore()
    default_before = st.current_db
    res = st.drop_database()
    actual = {
        "default_target": default_before,
        "drop_response": res,
        "demo_db_untouched": "demo_db" in st.show_dbs(),
    }
    expected = {
        "default_target": "test",
        "drop_response": {"dropped": "test", "ok": 1},
        "demo_db_untouched": True,
    }
    return {
        "name": "drop_default_test_database",
        "summary": "验证未切换库时 db.dropDatabase() 默认删除当前 test 数据库而不影响其他库。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_drop_collection_workflow():
    st = MiniMongoDropStore()
    st.use("demo_db")
    st.create_collection("temp_col")
    cols_before = st.show_collections()
    first_drop = st.drop_collection("temp_col")
    second_drop = st.drop_collection("temp_col")
    cols_after = st.show_collections()
    actual = {
        "cols_before": cols_before,
        "first_drop": first_drop,
        "second_drop": second_drop,
        "cols_after": cols_after,
    }
    expected = {
        "cols_before": ["logs", "site", "temp_col"],
        "first_drop": True,
        "second_drop": False,
        "cols_after": ["logs", "site"],
    }
    return {
        "name": "drop_collection_workflow",
        "summary": "验证 db.collection.drop() 删除已有集合返回 true、再次删除返回 false 并更新 show collections。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_idempotent_drop_empty_db():
    st = MiniMongoDropStore()
    st.use("ghost_db")
    res = st.drop_database()
    actual = {"response": res, "admin_intact": "admin" in st.show_dbs()}
    expected = {"response": {"ok": 1}, "admin_intact": True}
    return {
        "name": "idempotent_drop_empty_db",
        "summary": "验证对未落盘或空数据库调用 db.dropDatabase() 安全返回 {ok: 1} 且不波及系统库。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_drop_database_workflow(),
        case_drop_default_test_database(),
        case_drop_collection_workflow(),
        case_idempotent_drop_empty_db(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
验证 dropDatabase 返回 {dropped, ok:1}、系统库不受影响、collection.drop() 首次 true 二次 false 及空库安全返回。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:MongoDB

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

下载课程关联工程包:MongoDB

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

会删除连接后默认激活的 `test` 数据库;因此在执行任何删除操作前都应先用 `db` 核实当前库名。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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