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

MongoDB 覆盖索引查询

系统解析 MongoDB 覆盖索引查询(Covered Query)的判定条件、_id 显式排除要求、createIndex() 替代 ensureIndex() 的版本变更以及数组/子文档限制,并在离线索引评估器中验证 totalDocsExamined=0。

学完这一章,你能够

  • 系统解析 MongoDB 覆盖索引查询(Covered Query)的判定条件、_id 显式排除要求、createIndex() 替代 ensureIndex() 的版本变更以及数组/子文档限制,并在离线索引评估器中验证 totalDocsExamined=0。

覆盖索引查询定义与性能优势

按照 MongoDB 官方定义,当一条查询同时满足两个条件——所有查询条件字段都属于同一个索引的一部分,且所有投影返回字段也全部包含在该索引键中——即可触发覆盖索引查询(Covered Query)。此时数据库引擎仅靠遍历常驻内存的索引 B-Tree 就能直接组装结果,完全无需回表读取磁盘或缓存中的原始数据文档(`totalDocsExamined` 为 0),从而显著降低 I/O 延迟。

创建复合索引、排除 _id 与不可覆盖边界

在包含 `gender`、`user_name` 等字段的 `users` 集合上,先执行 `db.users.createIndex({gender: 1, user_name: 1})` 建立复合索引(注意:早期版本常见的 `ensureIndex()` 已在 MongoDB 5.0 中彻底移除,现代版本统一使用 `createIndex()`)。随后执行 `db.users.find({gender: "M"}, {user_name: 1, _id: 0})`,查询条件 `gender` 与返回字段 `user_name` 全部落在同一复合索引内,实现纯索引覆盖扫描(`PROJECTION_COVERED`)。

由于 MongoDB 默认会在投影结果中附带 `_id` 字段,而上述复合索引并未包含 `_id`,若忘记写 `_id: 0`(例如 `db.users.find({gender: "M"}, {user_name: 1})`),引擎就必须回表 `FETCH` 原始文档读取 `_id`,覆盖查询随之失效。此外,当被索引的字段是数组(多键索引)或涉及整块子文档投影等限制场景时,同样无法直接通过覆盖查询免除回表。离线评估器已对覆盖命中、漏排 `_id`、数组与子文档四种情况逐一验证。

离线验证覆盖查询 PROJECTION_COVERED (totalDocsExamined=0) 与非覆盖边界条件

含完整源码 · 135 行
展开查看收起
python
"""Offline MongoDB covered query eligibility & projection verifier."""
import json

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


def evaluate_covered_query(docs, index_fields, query_filter, projection):
    idx_set = set(index_fields)
    is_multikey = any(
        isinstance(d.get(f), list) for d in docs for f in index_fields
    )
    has_subdoc = any(
        isinstance(d.get(f), dict) or "." in f for d in docs for f in index_fields
    )
    query_fields = set(query_filter.keys())
    include_id = projection.get("_id", 1) != 0
    returned_fields = {k for k, v in projection.items() if k != "_id" and v == 1}
    if include_id:
        returned_fields.add("_id")

    covered = (
        query_fields.issubset(idx_set)
        and returned_fields.issubset(idx_set)
        and not is_multikey
        and not has_subdoc
    )

    # Execute actual projection on matching docs
    matched = [
        d for d in docs if all(d.get(k) == v for k, v in query_filter.items())
    ]
    projected = [{f: d[f] for f in sorted(returned_fields) if f in d} for d in matched]
    return {
        "covered": covered,
        "totalDocsExamined": 0 if covered else len(matched),
        "totalKeysExamined": len(matched),
        "stage": "PROJECTION_COVERED" if covered else "FETCH",
        "results": projected,
    }


def main():
    users = [
        {
            "_id": "53402597d852426020000002",
            "contact": "987654321",
            "dob": "01-01-1991",
            "gender": "M",
            "name": "Tom Benzamin",
            "user_name": "tombenzamin",
            "tags": ["nosql", "db"],
            "profile": {"tier": "gold"},
        },
        {
            "_id": "53402597d852426020000003",
            "contact": "123456789",
            "dob": "05-06-1993",
            "gender": "F",
            "name": "Alice Lin",
            "user_name": "alicelin",
            "tags": ["cloud"],
            "profile": {"tier": "silver"},
        },
    ]

    # Case 1: Covered query on compound index {gender: 1, user_name: 1} with _id: 0
    r_covered = evaluate_covered_query(
        users,
        ["gender", "user_name"],
        {"gender": "M"},
        {"user_name": 1, "_id": 0},
    )
    c1_actual = r_covered
    c1_expected = {
        "covered": True,
        "totalDocsExamined": 0,
        "totalKeysExamined": 1,
        "stage": "PROJECTION_COVERED",
        "results": [{"user_name": "tombenzamin"}],
    }

    # Case 2: Non-covered when _id is not excluded, or when index covers array/subdocument fields
    r_with_id = evaluate_covered_query(
        users,
        ["gender", "user_name"],
        {"gender": "M"},
        {"user_name": 1},
    )
    r_array = evaluate_covered_query(
        users,
        ["tags"],
        {"tags": "nosql"},
        {"tags": 1, "_id": 0},
    )
    r_subdoc = evaluate_covered_query(
        users,
        ["profile"],
        {"profile": {"tier": "gold"}},
        {"profile": 1, "_id": 0},
    )
    c2_actual = {
        "with_default_id_covered": r_with_id["covered"],
        "with_default_id_docs_examined": r_with_id["totalDocsExamined"],
        "array_index_covered": r_array["covered"],
        "subdoc_index_covered": r_subdoc["covered"],
    }
    c2_expected = {
        "with_default_id_covered": False,
        "with_default_id_docs_examined": 1,
        "array_index_covered": False,
        "subdoc_index_covered": False,
    }

    cases = [
        {
            "name": "covered_query_zero_doc_fetch",
            "summary": "Verify compound index {gender: 1, user_name: 1} with {_id: 0, user_name: 1} achieves totalDocsExamined=0.",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "uncovered_default_id_array_and_subdoc",
            "summary": "Verify omitting _id: 0 or indexing array/subdocument fields forces FETCH instead of covered scan.",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
离线评估器验证 {gender:1, user_name:1} 索引配合 {_id:0, user_name:1} 实现 0 次文档回表,而保留 _id、数组多键或子文档字段均回退到 FETCH。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:MongoDB

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

下载课程关联工程包:MongoDB

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

因为 MongoDB 投影默认包含 _id 字段,而 {gender: 1, user_name: 1} 索引中并没有 _id;必须显式加上 _id: 0 才能避免回表读取原始文档。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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