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

MongoDB 删除集合

讲解 MongoDB 使用 db.collection.drop() 永久删除集合及其全部文档与二级索引的语法、布尔返回值及前后核验步骤。

学完这一章,你能够

  • 讲解 MongoDB 使用 db.collection.drop() 永久删除集合及其全部文档与二级索引的语法、布尔返回值及前后核验步骤。

db.collection.drop() 语法与返回值语义

在 MongoDB 中删除整张集合使用无参方法 `db.<collection>.drop()`(现代版本可选传写关注选项对象,常规无需传参)。该操作会不可逆地永久移除目标集合中的全部文档及关联的所有二级索引,因此在生产环境中执行前须充分确认并做好备份。方法执行后返回布尔值:目标集合存在且删除成功返回 `true`,若集合原本不存在则返回 `false`。

删除集合的完整查验步骤

规范的操作步骤如下:先执行 `use mydb` 切入目标库并运行 `show collections` 列出当前库已有集合(例如 `mycol`、`mycol2`、`demo`);随后运行 `db.mycol2.drop()` 并确认返回 `true`;最后再次执行 `show collections` 核实 `mycol2` 已消失,而同库中的兄弟集合不受任何波及。本站离线验证器实测了成功返回 `true`、缺失返回 `false`、同库隔离及删后重建不含旧索引的完整行为。

运行 db.collection.drop() 存在/缺失布尔返回值、同库集合隔离与不可逆清理验证

含完整源码 · 113 行
展开查看收起
python
"""Offline MongoDB db.collection.drop() verifier (Ch15 delete-collection)."""
import json

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


def make_mydb():
    return {
        "mycol": {"docs": [{"_id": 1, "k": "a"}], "indexes": ["_id_"]},
        "mycol2": {"docs": [{"_id": 2, "k": "b"}, {"_id": 3, "k": "c"}], "indexes": ["_id_", "k_1"]},
        "demo": {"docs": [{"_id": 4, "k": "d"}], "indexes": ["_id_"]},
    }


def drop_collection(db: dict, name: str) -> bool:
    if name in db:
        del db[name]
        return True
    return False


def case_drop_existing_collection_returns_true():
    db = make_mydb()
    before = sorted(db.keys())
    dropped = drop_collection(db, "mycol2")
    after = sorted(db.keys())
    actual = {"before": before, "drop_return": dropped, "after": after}
    expected = {
        "before": ["demo", "mycol", "mycol2"],
        "drop_return": True,
        "after": ["demo", "mycol"],
    }
    return {
        "name": "drop_existing_collection_returns_true",
        "summary": "验证 db.mycol2.drop() 删除已存在集合返回 true 并从 show collections 移除。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_drop_missing_collection_returns_false():
    db = make_mydb()
    res = drop_collection(db, "nonexistent_col")
    actual = {"drop_return": res, "collection_count": len(db)}
    expected = {"drop_return": False, "collection_count": 3}
    return {
        "name": "drop_missing_collection_returns_false",
        "summary": "验证对不存在的集合调用 drop() 返回 false 且不抛出异常。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_drop_isolation_across_collections():
    db = make_mydb()
    drop_collection(db, "mycol2")
    actual = {
        "mycol_docs": db["mycol"]["docs"],
        "demo_docs": db["demo"]["docs"],
    }
    expected = {
        "mycol_docs": [{"_id": 1, "k": "a"}],
        "demo_docs": [{"_id": 4, "k": "d"}],
    }
    return {
        "name": "drop_isolation_across_collections",
        "summary": "验证删除 mycol2 不会波及同库中其他集合 mycol 与 demo 的数据。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_irreversible_drop_and_recreate():
    db = make_mydb()
    drop_collection(db, "mycol2")
    after_drop_exists = "mycol2" in db
    # Recreate via fresh insert: old documents are permanently gone
    db["mycol2"] = {"docs": [{"_id": 100, "k": "fresh"}], "indexes": ["_id_"]}
    actual = {
        "existed_after_drop": after_drop_exists,
        "recreated_ids": [d["_id"] for d in db["mycol2"]["docs"]],
        "old_secondary_index_gone": "k_1" not in db["mycol2"]["indexes"],
    }
    expected = {
        "existed_after_drop": False,
        "recreated_ids": [100],
        "old_secondary_index_gone": True,
    }
    return {
        "name": "irreversible_drop_and_recreate",
        "summary": "验证 drop() 不可逆地清除旧文档与二级索引,后续重建集合从空状态开始。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_drop_existing_collection_returns_true(),
        case_drop_missing_collection_returns_false(),
        case_drop_isolation_across_collections(),
        case_irreversible_drop_and_recreate(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
验证删除已存在集合返回 true、不存在返回 false、兄弟集合不受影响且旧二级索引被彻底清除。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:MongoDB

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

下载课程关联工程包:MongoDB

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

`deleteMany({})` 逐条删除文档但保留集合配置与全部二级索引,大集合上耗时且产生大量 oplog;`drop()` 直接丢弃整张集合与所有二级索引,瞬时释放空间但不可逆且重建时需重设索引。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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