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

MongoDB 正则表达式

系统梳理 MongoDB PCRE 正则查询语法($regex 与字面量 /pattern/)、不区分大小写选项 $options:'i'(纠正早期 $i 笔误)、数组元素正则匹配、前缀锚定索引优化及动态变量防注入安全写法,并在离线引擎中验证。

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

学完这一章,你能够

PCRE 正则基础语法与大小写不敏感选项

正则表达式使用模式字符串描述并匹配符合特定词法规则的文本。MongoDB 内置 PCRE(Perl Compatible Regular Expression)引擎,通过 `$regex` 查询操作符或正则字面量直接对字符串字段执行匹配,且无需像全文检索那样事先建立专用索引即可开箱即用。

在 `posts` 集合中查找 `post_text` 包含某子串的文档,既可写作 `db.posts.find({post_text: {$regex: "devhub"}})`,也可简写为字面量 `db.posts.find({post_text: /devhub/})`。若需忽略大小写,应配合 `$options: "i"`——即 `{post_text: {$regex: "devhub", $options: "i"}}`(或 `/devhub/i`)。需要特别纠正的是:早期部分教程误将选项写作 `$options: "$i"` 或 `$Option`,实际 MongoDB 官方语法键名严格区分大小写为 `$options` 且合法标志字符为 `"i"`/`"m"`/`"x"`/`"s"`(不带 `$` 前缀)。

数组元素匹配、前缀索引优化与动态变量安全构造

`$regex` 同样天然适用于字符串数组字段:对 `tags` 数组执行 `db.posts.find({tags: {$regex: "dev", $options: "i"}})` 时,只要数组中存在任意一个元素满足该正则模式,整篇文档即会被命中返回,非常适合标签模糊检索。

性能调优方面,常规非锚定正则(如 `/dev/`)与忽略大小写正则通常无法充分利用普通 B-Tree 索引的范围剪枝,容易触发全索引扫描或全表扫描;而区分大小写的**前缀锚定正则表达式**(以 `^` 开头,例如 `/^tut/`)则可以借助目标字段的 B-Tree 索引直接定位到 `[tut, tuu)` 区间大幅提速。此外,当需要把运行时变量拼入正则条件时,**切勿**沿用早期资料里的 `eval("/" + key + "/i")`——`eval()` 存在严重的代码注入漏洞;现代安全写法应先对用户输入中的正则元字符进行转义,再传入 `new RegExp(escapedKey, "i")` 或 `{$regex: escapedKey, $options: "i"}`。离线验证脚本已对大小写敏感/不敏感、数组匹配、前缀锚定与元字符安全转义(`c++` -> `c\+\+`)逐一验证。

离线验证 $regex 区分/忽略大小写、数组元素匹配、^前缀锚定与安全元字符转义

python · 阅读源码
"""Offline MongoDB $regex, $options:'i', array matching & prefix optimization verifier."""
import json
import re

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


def regex_find(docs, field, pattern, options=""):
    flags = 0
    if "i" in options:
        flags |= re.IGNORECASE
    if "m" in options:
        flags |= re.MULTILINE
    if "s" in options:
        flags |= re.DOTALL
    compiled = re.compile(pattern, flags)
    matched = []
    for d in docs:
        val = d.get(field)
        if isinstance(val, list):
            if any(isinstance(el, str) and compiled.search(el) for el in val):
                matched.append(d)
        elif isinstance(val, str) and compiled.search(val):
            matched.append(d)
    return matched


def main():
    posts = [
        {"_id": 1, "post_text": "enjoy the mongodb articles on devhub", "tags": ["mongodb", "devhub"]},
        {"_id": 2, "post_text": "hey! this is my post on DevHub", "tags": ["DevHub", "tutorial"]},
        {"_id": 3, "post_text": "tut-01: prefix index optimization", "tags": ["tut", "perf"]},
    ]

    # Case 1: Case-sensitive $regex vs case-insensitive $options: "i"
    cs_hits = [d["_id"] for d in regex_find(posts, "post_text", "devhub")]
    ci_hits = [d["_id"] for d in regex_find(posts, "post_text", "devhub", options="i")]
    c1_actual = {"case_sensitive_ids": cs_hits, "case_insensitive_ids": ci_hits}
    c1_expected = {"case_sensitive_ids": [1], "case_insensitive_ids": [1, 2]}

    # Case 2: Regex matching inside array field (`tags`)
    arr_hits = [d["_id"] for d in regex_find(posts, "tags", "dev", options="i")]
    c2_actual = {"matched_array_doc_ids": arr_hits}
    c2_expected = {"matched_array_doc_ids": [1, 2]}

    # Case 3: Prefix regex (^tut) indexability & safe dynamic variable escaping (no eval)
    user_input = "tut-01"
    safe_pattern = f"^{re.escape(user_input)}"
    prefix_hits = [d["_id"] for d in regex_find(posts, "post_text", safe_pattern)]
    # Compare against unescaped metacharacter input (e.g. "c++")
    escaped_cpp = re.escape("c++")
    c3_actual = {
        "prefix_anchored": safe_pattern.startswith("^"),
        "prefix_hits": prefix_hits,
        "safe_escaped_cpp": escaped_cpp,
    }
    c3_expected = {
        "prefix_anchored": True,
        "prefix_hits": [3],
        "safe_escaped_cpp": r"c\+\+",
    }

    cases = [
        {
            "name": "regex_case_sensitive_vs_options_i",
            "summary": "Verify $regex matches exact case by default and matches mixed case with $options: 'i'.",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "regex_array_element_matching",
            "summary": "Verify $regex matches when any string element in the tags array satisfies the pattern.",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "regex_prefix_optimization_and_safe_escape",
            "summary": "Verify anchored ^prefix pattern and safe regex escaping for dynamic variables without eval().",
            "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()
预期结果 · 待实际运行核验
  • 在离线正则引擎中确认默认区分大小写仅命中 1 条、$options:'i' 命中 2 条、数组 tags 命中 2 条、^tut-01 前缀命中 1 条且 c++ 正确转义为 c\+\+。
离线验证 $regex 区分/忽略大小写、数组元素匹配、^前缀锚定与安全元字符转义

所需环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。

当前源码 SHA256:e9730817015cc6b79feddd359e672861b7d2abf951ef5f08741fc7df050209bc

下载本站示例源码

本地运行

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

下载MongoDB 正则表达式实验

所需环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。

ZIP SHA256:ed456d4bee1c2d16267c606b67c4b47849455b7f36792f2a89cde0c89d4a07d4

常见错误与边界

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

练习与解答

为什么在 MongoDB 中将正则写成 /^tut/ 比 /tut/ 更容易利用普通 B-Tree 索引?

展开参考解答

B-Tree 索引按字符字典序排列,左锚定前缀 /^tut/(且区分大小写)可转化为有序区间 ['tut', 'tuu') 的索引范围扫描;而不带 ^ 的 /tut/ 无法界定起始键,只能扫描整个索引或全集合。

规范与官方依据