MongoDB 索引限制
系统梳理 MongoDB 索引的写入额外开销、内存工作集约束、难以利用索引的查询操作符、1024 字节历史索引键上限(2.6–4.0 与 4.2+ 演进)及 64 索引/31-32 复合字段等核心边界,并完成离线边界校验。
学完这一章,你能够
- 系统梳理 MongoDB 索引的写入额外开销、内存工作集约束、难以利用索引的查询操作符、1024 字节历史索引键上限(2.6–4.0 与 4.2+ 演进)及 64 索引/31-32 复合字段等核心边界,并完成离线边界校验。
写入开销、内存工作集与查询操作符限制
索引以空间与写入成本换取读取性能:每个索引都会占用额外磁盘与缓存空间,每次插入、更新(涉及索引键变更)或删除文档时引擎都必须同步维护全部相关索引。因此对于极少读取、以纯日志写入为主的集合,应尽量避免创建多余索引。
为了获得低延迟检索,活跃索引工作集应尽量完整容纳在内存(RAM)中。当索引总大小超出可用缓存容量时,存储引擎(如 WiredTiger)会持续将热索引页换出到磁盘引发大量磁盘随机 I/O(注意:引擎是驱逐内存缓存页导致性能骤降,并不会删除集合上的索引定义本身)。
并非所有查询条件都能高效利用标准 B-Tree 索引:非左锚定正则表达式、否定类操作符(如 `$nin`、`$not`)、取模算术运算符 `$mod` 以及执行 JavaScript 的 `$where` 子句通常无法直接通过索引范围定位(前缀锚定正则 `^prefix` 除外)。养成用 `explain("executionStats")` 验证执行计划的习惯是排查慢查询的关键。
1024 字节索引键上限演进与集合最大范围
在索引键长度限制方面需区分版本演进:自 MongoDB 2.6 起至 4.0 版本,单条索引键总大小严格受限于 `1024` 字节——若现有文档字段超长则建索引失败,向已建索引集合插入超长文档(或通过 `mongorestore`/`mongoimport` 导入)也会被拒;从 MongoDB 4.2 起,WiredTiger 引擎已经移除了 1024 字节的硬性索引键长度上限,但生产设计仍应避免对超大长文本建立普通 B-Tree 索引(长文本检索应使用全文索引或哈希摘要)。
集合结构方面存在若干硬性或历史上限:单个集合最多只能创建 `64` 个索引(含默认 `_id_` 索引);历史版本(4.2 之前)完整索引命名空间长度上限为 `128` 字节(4.2+ 已放宽该限制);单个复合索引最多包含 `32` 个字段(早期 4.x 及以前版本上限为 `31` 个字段)。离线校验脚本已对 64 索引上限、31/32 复合字段上限、128 字节索引名、1024 字节键边界以及 7 类查询操作符的索引可用性逐项验证。
离线校验 64 索引上限、31/32 复合字段、1024 字节历史键限制与非索引操作符
"""Offline MongoDB index limits, query restrictions & 1024-byte key boundary verifier."""
import json
VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"
MAX_INDEXES_PER_COLLECTION = 64
MAX_COMPOUND_FIELDS_LEGACY = 31
MAX_COMPOUND_FIELDS_MODERN = 32
LEGACY_MAX_INDEX_KEY_BYTES = 1024
LEGACY_MAX_INDEX_NAME_BYTES = 128
def check_index_limits(existing_count, field_names, index_name):
errors = []
if existing_count >= MAX_INDEXES_PER_COLLECTION:
errors.append("max_64_indexes_exceeded")
if len(field_names) > MAX_COMPOUND_FIELDS_MODERN:
errors.append("max_compound_fields_exceeded")
if len(index_name.encode("utf-8")) > LEGACY_MAX_INDEX_NAME_BYTES:
errors.append("legacy_128_byte_name_exceeded")
return {"allowed": len(errors) == 0, "errors": errors}
def check_legacy_key_size(value_str):
# BSON index key payload check for MongoDB 2.6-4.0 (removed in 4.2+ WiredTiger)
size_bytes = len(value_str.encode("utf-8"))
return {"bytes": size_bytes, "within_legacy_1024_limit": size_bytes < LEGACY_MAX_INDEX_KEY_BYTES}
def query_uses_standard_btree_index(op_name, pattern=None):
if op_name in {"$nin", "$not", "$mod", "$where"}:
return False
if op_name == "$regex":
return bool(pattern and pattern.startswith("^"))
return op_name in {"$eq", "$gt", "$gte", "$lt", "$lte", "$in"}
def main():
# Case 1: Hard structural limits (64 indexes, 31/32 compound fields, 128-byte historical name limit)
ok_res = check_index_limits(10, ["a", "b"], "a_1_b_1")
over_64 = check_index_limits(64, ["a"], "a_1")
over_fields = check_index_limits(5, [f"f{i}" for i in range(33)], "compound_33")
over_name = check_index_limits(5, ["x"], "x" * 130)
c1_actual = {
"valid_index_allowed": ok_res["allowed"],
"index_65_errors": over_64["errors"],
"compound_33_errors": over_fields["errors"],
"name_130_errors": over_name["errors"],
"legacy_vs_modern_compound_cap": [MAX_COMPOUND_FIELDS_LEGACY, MAX_COMPOUND_FIELDS_MODERN],
}
c1_expected = {
"valid_index_allowed": True,
"index_65_errors": ["max_64_indexes_exceeded"],
"compound_33_errors": ["max_compound_fields_exceeded"],
"name_130_errors": ["legacy_128_byte_name_exceeded"],
"legacy_vs_modern_compound_cap": [31, 32],
}
# Case 2: Legacy 1024-byte key size boundary (MongoDB 2.6-4.0 vs 4.2+)
small_key = check_legacy_key_size("a" * 512)
oversized_key = check_legacy_key_size("a" * 1200)
c2_actual = {
"small_key_ok": small_key["within_legacy_1024_limit"],
"oversized_key_ok": oversized_key["within_legacy_1024_limit"],
"oversized_bytes": oversized_key["bytes"],
}
c2_expected = {
"small_key_ok": True,
"oversized_key_ok": False,
"oversized_bytes": 1200,
}
# Case 3: Query operators that cannot use standard B-tree index efficiently
ops = {
"$eq": query_uses_standard_btree_index("$eq"),
"$nin": query_uses_standard_btree_index("$nin"),
"$not": query_uses_standard_btree_index("$not"),
"$mod": query_uses_standard_btree_index("$mod"),
"$where": query_uses_standard_btree_index("$where"),
"regex_unanchored": query_uses_standard_btree_index("$regex", "mongo"),
"regex_prefix": query_uses_standard_btree_index("$regex", "^mongo"),
}
c3_actual = ops
c3_expected = {
"$eq": True,
"$nin": False,
"$not": False,
"$mod": False,
"$where": False,
"regex_unanchored": False,
"regex_prefix": True,
}
cases = [
{
"name": "collection_index_and_compound_limits",
"summary": "Verify 64-index cap, 31/32 compound field limit, and 128-byte historical index name limit.",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "legacy_1024_byte_key_limit_boundary",
"summary": "Verify 1024-byte legacy index key limit rejects 1200-byte keys while accepting 512-byte keys.",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "non_indexable_query_operators",
"summary": "Verify $nin, $not, $mod, $where, and unanchored regex bypass standard index scans unlike $eq and ^prefix regex.",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 在离线规则引擎中确认第 65 个索引、33 字段复合索引、130 字节超长索引名及 1200 字节历史键均被拦截,并区分 $eq/^prefix 与 $nin/$not/$mod/$where 的索引能力。
所需环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。
当前源码 SHA256:220ce105cc9c59b1633fe9ebe6f6f911e6f6d356db0ebb21ded6d976ffd37197
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。
ZIP SHA256:2de9ae984506f817365596189d70558b02a1df7982cc3b4324b272ab982cf4dc
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 MongoDB 4.2 及更高版本中,早期 2.6 版本引入的 1024 字节索引键上限和 31 个复合索引字段上限有哪些变化?
展开参考解答
MongoDB 4.2+ 移除了 WiredTiger 引擎下 1024 字节索引键长度硬限制与 128 字节索引名长度限制,同时将单个复合索引最大字段数从 31 提升到 32;单个集合最多 64 个索引的上限依然保留。