蓝色天空网mbsky.com · 知识 · 实践 · 创造MongoDB · 本地阅读预览
教程 / 数据库 / MongoDB

MongoDB 删除数据库

讲解 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() 及空库幂等删除验证

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 及空库安全返回。
运行 db.dropDatabase() 全流程、默认 test 库删除、collection.drop() 及空库幂等删除验证

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:2535441e863fbbdbc72dedb226702fda09cb368d796927b5b1925232e2072465

下载本站示例源码

本地运行

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

下载MongoDB 删除数据库实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:8a125f67b5dcaba0b8b128bafd9f7aec69bfd25fe92eed0ced42573023fa6c7e

常见错误与边界

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

练习与解答

如果不小心在 `mongosh` 中未切换库直接运行了 `db.dropDatabase()`,会删除哪个数据库?

展开参考解答

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

规范与官方依据