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

MongoDB 索引

系统剖析 MongoDB 索引原理与常见索引类型(单字段、复合、文本、地理空间、哈希),createIndex() 语法与选项(unique/sparse/TTL/weights)、getIndexes/dropIndex 管理及索引策略与写入权衡。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

索引原理与常见索引类型

索引是按一个或多个字段值有序组织的高效检索数据结构(MongoDB 常规索引底层为 B-tree)。缺乏索引时,查询只能触发全集合扫描(`COLLSCAN`),逐条读取并比对集合内每一份文档,数据规模上升后耗时会从毫秒恶化至数十秒。MongoDB 常见索引类型涵盖五大类:基于单键的**单字段索引**、基于多键组合并遵循最左前缀规则的**复合索引**、支撑分词搜索的**文本索引**、面向球面或平面坐标的**地理空间索引**(`2dsphere` / `2d`),以及将键值哈希散列以适配均匀分片或等值查找的**哈希索引**(`hashed`)。

createIndex() 语法、历史 ensureIndex 与核心选项

创建索引使用 `db.collection.createIndex(keys, options)`(注意 3.0.0 之前旧名为 `ensureIndex()`,3.0 起改用 `createIndex()` 并在 MongoDB 5.0 中正式移除了 `ensureIndex()`)。其中 `db` 为数据库对象、`collection` 为集合名、`keys` 指定字段与方向(`1` 升序、`-1` 降序或 `"text"`/`"2dsphere"`/`"hashed"` 等类型标识)、`options` 为可选配置对象。

`options` 常用参数包括:`unique: true` 建立唯一索引以阻断重复键写入;`background: true` 在历史版本中用于避免阻塞前台操作(MongoDB 4.2 起已采用混合无阻塞建索引并忽略 `background` 参数);`name` 自定义索引名(省略时按 `<field>_<dir>` 自动生成);`sparse: true` 仅索引包含该字段的文档(可与 `unique: true` 组合允许多个文档缺失该键,现代也常用更灵活的 `partialFilterExpression` 部分索引);`expireAfterSeconds` 在日期字段上启用 TTL 自动过期清理;`v` 标识索引内部版本(通常不手设);`weights` 为文本索引分配字段权重。

各类索引创建、查看、删除与优化权衡

实操中可按需创建普通升序索引(`{ age: 1 }`)、唯一/稀疏索引、带权重的文本索引(`{ field: "text" }, { weights: { field: 10 } }`)、球面 `2dsphere` 与平面 `2d` 地理空间索引,以及哈希索引(`{ field: "hashed" }`,常用于哈希分片键以分散写入热点,不支持范围查询)。维护阶段通过 `db.collection.getIndexes()` 查看全部索引元数据,通过 `db.collection.dropIndex("indexName")` 删除单个索引,或以 `db.collection.dropIndexes()` 一键移除除系统默认 `_id_` 之外的所有二级索引。

设计索引须兼顾读取收益与写入成本:选键时优先覆盖高查询频率与高字段基数(唯一值占比高)的字段,并控制索引体积使热点索引能够常驻工作集内存;对高频联合条件优先设计复合索引(遵循 ESR 等值-排序-范围原则),并定期借助 `explain()` 监控索引命中率。切记每新增一个二级索引,都会放大每次插入、更新和删除时的索引维护开销并占用额外磁盘与内存空间,切忌盲目全字段建索引。

运行 B-tree 索引查找、unique+sparse 约束、TTL 过期淘汰、文本/地理/哈希索引及写入放大验证

python · 阅读源码
"""Offline MongoDB B-tree, compound, unique, sparse, TTL, text/geo/hashed index verifier (Ch24 indexing)."""
import bisect
import datetime
import hashlib
import json
import math

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


class OfflineIndexedCollection:
    def __init__(self):
        self.docs = []
        self.indexes = {
            "_id_": {"keys": [("_id", 1)], "unique": True, "sparse": False, "entries": []},
        }
        self.index_write_ops = 0

    @staticmethod
    def auto_name(keys: list[tuple[str, int | str]]) -> str:
        return "_".join(f"{k}_{v}" for k, v in keys)

    def create_index(self, keys: list[tuple[str, int | str]], unique=False, sparse=False, name=None, expire_after_seconds=None, weights=None):
        idx_name = name or self.auto_name(keys)
        meta = {
            "keys": list(keys),
            "unique": unique,
            "sparse": sparse,
            "expireAfterSeconds": expire_after_seconds,
            "weights": weights,
            "entries": [],
        }
        for pos, d in enumerate(self.docs):
            self._index_doc(meta, d, pos)
        self.indexes[idx_name] = meta
        return idx_name

    def _index_doc(self, meta: dict, doc: dict, pos: int):
        fields = [k for k, _ in meta["keys"]]
        if meta["sparse"] and not any(f in doc for f in fields):
            return
        key_tuple = tuple(doc.get(f) for f in fields)
        if meta["unique"]:
            existing_keys = [k for k, _ in meta["entries"]]
            if key_tuple in existing_keys:
                raise ValueError(f"E11000 duplicate key: {key_tuple}")
        bisect.insort(meta["entries"], (key_tuple, pos))
        self.index_write_ops += 1

    def insert_one(self, doc: dict):
        pos = len(self.docs)
        # Validate unique indexes before committing
        for meta in self.indexes.values():
            fields = [k for k, _ in meta["keys"]]
            if meta["sparse"] and not any(f in doc for f in fields):
                continue
            key_tuple = tuple(doc.get(f) for f in fields)
            if meta["unique"] and any(k == key_tuple for k, _ in meta["entries"]):
                raise ValueError(f"E11000 duplicate key: {key_tuple}")
        self.docs.append(dict(doc))
        for meta in self.indexes.values():
            self._index_doc(meta, doc, pos)

    def get_indexes(self) -> list[str]:
        return sorted(self.indexes.keys())

    def drop_index(self, idx_name: str):
        if idx_name == "_id_":
            raise ValueError("cannot drop _id index")
        return self.indexes.pop(idx_name, None) is not None

    def drop_indexes(self):
        for k in list(self.indexes.keys()):
            if k != "_id_":
                del self.indexes[k]


def case_single_and_compound_btree_index_lookup():
    col = OfflineIndexedCollection()
    for i in range(1, 51):
        col.insert_one({"_id": i, "age": 18 + (i % 40), "dept": "eng" if i % 2 == 0 else "ops"})
    col.create_index([("age", 1)])
    col.create_index([("dept", 1), ("age", -1)])

    # Full scan examines all 50 docs; B-tree bisect on age==57 examines only matching entries
    collscan_examined = len(col.docs)
    entries = col.indexes["age_1"]["entries"]
    target = (57,)
    lo = bisect.bisect_left(entries, (target, -1))
    hi = bisect.bisect_right(entries, (target, 10**9))
    ixscan_hits = [col.docs[pos]["_id"] for _, pos in entries[lo:hi]]

    # Compound prefix rule for ("dept", "age")
    compound_fields = [k for k, _ in col.indexes["dept_1_age_-1"]["keys"]]
    supports_dept = compound_fields[:1] == ["dept"]
    supports_dept_age = compound_fields[:2] == ["dept", "age"]
    supports_age_only = compound_fields[:1] == ["age"]

    actual = {
        "collscan_examined": collscan_examined,
        "ixscan_examined": len(ixscan_hits),
        "ixscan_ids": ixscan_hits,
        "compound_prefix_checks": [supports_dept, supports_dept_age, supports_age_only],
    }
    expected = {
        "collscan_examined": 50,
        "ixscan_examined": 1,
        "ixscan_ids": [39],
        "compound_prefix_checks": [True, True, False],
    }
    return {
        "name": "single_and_compound_btree_index_lookup",
        "summary": "对比全集合扫描(50 文档)与 B-tree 索引二分查找(1 文档),并验证复合索引最左前缀规则。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_unique_and_sparse_index_constraints():
    col = OfflineIndexedCollection()
    col.create_index([("email", 1)], unique=True, sparse=True)
    col.insert_one({"_id": 1, "email": "alice@example.com"})
    # Sparse unique index allows multiple docs missing the email field!
    col.insert_one({"_id": 2, "name": "no_email_1"})
    col.insert_one({"_id": 3, "name": "no_email_2"})
    dup_rejected = False
    try:
        col.insert_one({"_id": 4, "email": "alice@example.com"})
    except ValueError:
        dup_rejected = True

    actual = {
        "indexed_entries_count": len(col.indexes["email_1"]["entries"]),
        "total_docs_stored": len(col.docs),
        "duplicate_email_rejected": dup_rejected,
    }
    expected = {
        "indexed_entries_count": 1,
        "total_docs_stored": 3,
        "duplicate_email_rejected": True,
    }
    return {
        "name": "unique_and_sparse_index_constraints",
        "summary": "验证 unique + sparse 索引拒绝重复 email,同时跳过缺失该字段的文档。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_ttl_expire_after_seconds_eviction():
    now = datetime.datetime(2026, 6, 1, 12, 0, 0, tzinfo=datetime.timezone.utc)
    ttl_seconds = 3600
    sessions = [
        {"_id": "s1", "createdAt": datetime.datetime(2026, 6, 1, 10, 0, 0, tzinfo=datetime.timezone.utc)},
        {"_id": "s2", "createdAt": datetime.datetime(2026, 6, 1, 11, 30, 0, tzinfo=datetime.timezone.utc)},
        {"_id": "s3", "createdAt": datetime.datetime(2026, 6, 1, 11, 55, 0, tzinfo=datetime.timezone.utc)},
    ]
    surviving = [
        s["_id"]
        for s in sessions
        if (now - s["createdAt"]).total_seconds() < ttl_seconds
    ]
    expected = ["s2", "s3"]
    return {
        "name": "ttl_expire_after_seconds_eviction",
        "summary": "验证 expireAfterSeconds: 3600 TTL 索引自动清理超时会话并保留有效文档。",
        "expected": expected,
        "actual": surviving,
        "passed": surviving == expected,
    }


def case_text_weights_geo_and_hashed_indexes():
    # Weighted text scoring: title weight 10 vs body weight 1
    docs = [
        {"id": 1, "title": "MongoDB Indexing", "body": "guide"},
        {"id": 2, "title": "Database Guide", "body": "indexing tips for indexing speed"},
    ]
    weights = {"title": 10, "body": 1}
    scores = {}
    for d in docs:
        s = sum(d[f].lower().split().count("indexing") * w for f, w in weights.items())
        scores[d["id"]] = s
    ranked = sorted(scores, key=lambda i: scores[i], reverse=True)

    # 2d planar distance & hashed bucket
    pts = [("p1", (0.0, 0.0)), ("p2", (3.0, 4.0)), ("p3", (10.0, 10.0))]
    within_6 = [pid for pid, (x, y) in pts if math.hypot(x, y) <= 6.0]
    h_bucket = int(hashlib.md5(b"shard_key_42").hexdigest(), 16) % 4

    actual = {
        "weighted_text_rank": ranked,
        "scores": scores,
        "geo_2d_within_6": within_6,
        "hashed_bucket_in_range": 0 <= h_bucket < 4,
    }
    expected = {
        "weighted_text_rank": [1, 2],
        "scores": {1: 10, 2: 2},
        "geo_2d_within_6": ["p1", "p2"],
        "hashed_bucket_in_range": True,
    }
    return {
        "name": "text_weights_geo_and_hashed_indexes",
        "summary": "验证文本索引 weights 权重排序、2d 平面距离筛选与 hashed 索引分桶分布。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_index_management_get_drop_and_write_overhead():
    col = OfflineIndexedCollection()
    n1 = col.create_index([("age", 1)])
    n2 = col.create_index([("name", "text")], name="name_text_custom")
    before = col.get_indexes()
    col.index_write_ops = 0
    col.insert_one({"_id": 1, "age": 25, "name": "Alice"})
    writes_with_3_indexes = col.index_write_ops
    col.drop_index(n1)
    after_drop_one = col.get_indexes()
    col.drop_indexes()
    after_drop_all = col.get_indexes()
    actual = {
        "auto_name": n1,
        "custom_name": n2,
        "before_drop": before,
        "writes_per_insert_with_3_indexes": writes_with_3_indexes,
        "after_drop_age": after_drop_one,
        "after_drop_all_keeps_id": after_drop_all,
    }
    expected = {
        "auto_name": "age_1",
        "custom_name": "name_text_custom",
        "before_drop": ["_id_", "age_1", "name_text_custom"],
        "writes_per_insert_with_3_indexes": 3,
        "after_drop_age": ["_id_", "name_text_custom"],
        "after_drop_all_keeps_id": ["_id_"],
    }
    return {
        "name": "index_management_get_drop_and_write_overhead",
        "summary": "验证 createIndex 自动命名、getIndexes、dropIndex/dropIndexes(保留 _id_)及索引写入放大开销。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_single_and_compound_btree_index_lookup(),
        case_unique_and_sparse_index_constraints(),
        case_ttl_expire_after_seconds_eviction(),
        case_text_weights_geo_and_hashed_indexes(),
        case_index_management_get_drop_and_write_overhead(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 验证 B-tree 检索仅查 1 文档 vs 全扫 50 文档、复合索引前缀规则、unique+sparse、TTL 过期与 dropIndexes 保留 _id_。
运行 B-tree 索引查找、unique+sparse 约束、TTL 过期淘汰、文本/地理/哈希索引及写入放大验证

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

当前源码 SHA256:d9c5ecd99a5e0f35e9109b7fa5fb5616119b96257a0495e522e1f0ecee1d661a

下载本站示例源码

本地运行

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

下载MongoDB 索引实验

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

ZIP SHA256:80bc582631c4b6b421aae3e13f58393936210332becabdf5e9e5fb9c31791226

常见错误与边界

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

练习与解答

如果对集合执行 `db.users.dropIndexes()`,默认的主键索引 `_id_` 会被一起删除吗?为什么频繁写入的表不宜建过多索引?

展开参考解答

不会;`_id_` 索引受系统保护,无法被 `dropIndex()` 或 `dropIndexes()` 删除。每次插入/更新/删除文档都必须同步更新集合上的每一个受影响二级索引,索引过多会显著放大写 I/O 与内存占用。

规范与官方依据