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

MongoDB 条件操作符

系统梳理 MongoDB 五大类条件操作符:8 个比较操作符、4 个逻辑操作符、2 个元素操作符、3 个数组操作符及正则/全文/地理空间/$where 其他操作符。

学完这一章,你能够

  • 系统梳理 MongoDB 五大类条件操作符:8 个比较操作符、4 个逻辑操作符、2 个元素操作符、3 个数组操作符及正则/全文/地理空间/$where 其他操作符。

条件操作符分类与比较操作符

条件操作符是 MongoDB 查询语言(MQL)的表达核心,按职责分为五大类别:比较操作符、逻辑操作符、元素操作符、数组操作符,以及面向文本、正则与地理空间的其他操作符。

比较操作符共有 8 个,均以 `{ field: { $op: value } }` 形式作用于单个字段:`$eq`(等于)、`$ne`(不等于)、`$gt`(大于)、`$gte`(大于等于)、`$lt`(小于)、`$lte`(小于等于),以及集合成员判断 `$in`(字段值命中候选数组任一项,如 `{ age: { $in: [20, 25, 30] } }`)与 `$nin`(不在候选数组中)。

逻辑操作符与元素操作符

逻辑操作符共有 4 个:`$and` 要求数组内所有子条件同时成立(当对同一字段附加多个约束或组合嵌套表达式时尤为必要);`$or` 要求至少一个子条件成立;`$not` 对单字段操作符条件取反(需注意在 MongoDB 语义中 `{ age: { $not: { $gt: 25 } } }` 也会匹配不包含 `age` 字段的文档);`$nor` 要求数组内全部子条件均不成立。

元素操作符针对文档的无固定模式特性检查字段元数据:`$exists` 以布尔值判断文档是否包含指定键(区分显式存有 `null` 的字段与根本缺失该键的文档);`$type` 按 BSON 类型别名或数字代码精准筛选字段的实际存储类型(例如 `{ age: { $type: "int" } }`)。

数组操作符与正则、文本、地理空间及其他操作符

数组操作符专门处理列表与嵌套对象数组:`$all` 要求数组同时包含指定清单中的全部元素(与顺序无关,如 `{ tags: { $all: ["red", "blue"] } }` 或 `["mongodb", "database"]`);`$elemMatch` 要求数组中至少存在某一个元素同时满足多个子条件(避免对象数组里不同元素各自拼凑满足条件造成误命中);`$size` 精确匹配数组长度(如 `{ tags: { $size: 3 } }`,注意 `$size` 仅接受确定整数,不支持直接写范围比较)。

其余常用专项操作符包括:`$regex` 执行正则表达式匹配(如 `{ name: { $regex: /^John/ } }`);`$text` 在已建文本索引的字段上执行词元全文检索;`$where` 允许嵌入 JavaScript 表达式过滤(存在性能与安全风险,现代 MongoDB 强烈建议改用聚合 `$expr` 替代);地理空间查询则使用 `$near`(配合 `$maxDistance` 按距离近到远返回邻近点)与 `$geoWithin`(配合 `$centerSphere` 等几何体筛选区域内文档,须在位置字段建立 `2dsphere` 或 `2d` 索引)。

MongoDB 比较操作符速查表

操作符语义描述示例表达式
$eq匹配字段值等于指定值的文档{ age: { $eq: 25 } }
$ne匹配字段值不等于指定值(含缺失该字段)的文档{ age: { $ne: 25 } }
$gt匹配字段值严格大于指定值的文档{ age: { $gt: 25 } }
$gte匹配字段值大于或等于指定值的文档{ age: { $gte: 25 } }
$lt匹配字段值严格小于指定值的文档{ age: { $lt: 25 } }
$lte匹配字段值小于或等于指定值的文档{ age: { $lte: 25 } }
$in匹配字段值命中给定数组任一元素的文档{ age: { $in: [25, 30, 35] } }
$nin匹配字段值不在给定数组中(含缺失字段)的文档{ age: { $nin: [25, 30, 35] } }

MongoDB 逻辑操作符速查表

操作符语义描述示例表达式
$and逻辑与,要求数组中所有条件全部成立{ $and: [ { age: { $gt: 25 } }, { city: "New York" } ] }
$or逻辑或,满足数组中任意一个条件即命中{ $or: [ { age: { $lt: 25 } }, { city: "New York" } ] }
$not逻辑非,对字段级表达式取反(同时命中缺少该字段的文档){ age: { $not: { $gt: 25 } } }
$nor逻辑或非,要求数组中所有条件全部不成立{ $nor: [ { age: { $gt: 25 } }, { city: "New York" } ] }

MongoDB 元素操作符速查表

操作符语义描述示例表达式
$exists检查文档是否包含指定键(即使值为 null 也算存在){ age: { $exists: true } }
$type检查字段存储的实际 BSON 数据类型{ age: { $type: "int" } }

MongoDB 数组操作符速查表

操作符语义描述示例表达式
$all要求数组包含指定列表中的全部元素(不限顺序){ tags: { $all: ["red", "blue"] } }
$elemMatch要求数组内至少单个元素同时满足全部内嵌条件{ results: { $elemMatch: { score: { $gt: 80, $lt: 85 } } } }
$size要求数组元素个数严格等于指定整数{ tags: { $size: 3 } }

MongoDB 正则、文本、脚本与地理空间操作符速查表

操作符语义描述示例表达式
$regex按正则表达式匹配字符串字段{ name: { $regex: /^A/ } }
$text基于文本索引执行分词全文检索{ $text: { $search: "coffee" } }
$where使用 JavaScript 表达式过滤(已不推荐,优先改用 $expr){ $where: "this.age > 25" }
$near按球面或平面距离查找靠近指定坐标的文档db.collection.find({ location: { $near: [10, 20], $maxDistance: 1000 } })
$geoWithin查找落入指定几何区域内的地理坐标文档db.collection.find({ location: { $geoWithin: { $centerSphere: [[10, 20], 1] } } })

运行五大类共 22 个 MongoDB 条件操作符全覆盖离线验证

含完整源码 · 307 行
展开查看收起
python
"""Offline MongoDB comparison, logical, element, array, regex/text/geo query operators verifier (Ch20)."""
import json
import math
import re

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


def bson_type_name(val) -> str:
    if isinstance(val, bool):
        return "bool"
    if isinstance(val, int):
        return "int"
    if isinstance(val, float):
        return "double"
    if isinstance(val, str):
        return "string"
    if isinstance(val, list):
        return "array"
    if isinstance(val, dict):
        return "object"
    if val is None:
        return "null"
    return "unknown"


def eval_field_ops(doc: dict, field: str, cond: dict) -> bool:
    present = field in doc
    val = doc.get(field)
    for op, target in cond.items():
        if op == "$eq":
            if not present or val != target:
                return False
        elif op == "$ne":
            if present and val == target:
                return False
        elif op == "$gt":
            if not (present and isinstance(val, (int, float)) and not isinstance(val, bool) and val > target):
                return False
        elif op == "$gte":
            if not (present and isinstance(val, (int, float)) and not isinstance(val, bool) and val >= target):
                return False
        elif op == "$lt":
            if not (present and isinstance(val, (int, float)) and not isinstance(val, bool) and val < target):
                return False
        elif op == "$lte":
            if not (present and isinstance(val, (int, float)) and not isinstance(val, bool) and val <= target):
                return False
        elif op == "$in":
            if not present or val not in target:
                return False
        elif op == "$nin":
            if present and val in target:
                return False
        elif op == "$not":
            if eval_field_ops(doc, field, target):
                return False
        elif op == "$exists":
            if present != bool(target):
                return False
        elif op == "$type":
            if not present or bson_type_name(val) != target:
                return False
        elif op == "$all":
            if not (present and isinstance(val, list) and all(x in val for x in target)):
                return False
        elif op == "$size":
            if not (present and isinstance(val, list) and len(val) == target):
                return False
        elif op == "$elemMatch":
            if not (present and isinstance(val, list) and any(eval_query(el, target) for el in val if isinstance(el, dict))):
                return False
        elif op == "$regex":
            if not (present and isinstance(val, str) and re.search(target, val)):
                return False
    return True


def eval_query(doc: dict, query: dict) -> bool:
    for k, cond in query.items():
        if k == "$and":
            if not all(eval_query(doc, sub) for sub in cond):
                return False
        elif k == "$or":
            if not any(eval_query(doc, sub) for sub in cond):
                return False
        elif k == "$nor":
            if any(eval_query(doc, sub) for sub in cond):
                return False
        elif isinstance(cond, dict):
            if not eval_field_ops(doc, k, cond):
                return False
        else:
            if doc.get(k) != cond:
                return False
    return True


def haversine_meters(lon1, lat1, lon2, lat2) -> float:
    r = 6371000.0
    p1, p2 = math.radians(lat1), math.radians(lat2)
    dp = math.radians(lat2 - lat1)
    dl = math.radians(lon2 - lon1)
    a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
    return 2 * r * math.asin(math.sqrt(a))


def case_comparison_operators_all_eight():
    docs = [
        {"name": "u1", "age": 17},
        {"name": "u2", "age": 20},
        {"name": "u3", "age": 25},
        {"name": "u4", "age": 30},
        {"name": "u5", "age": 35},
    ]
    q = lambda flt: [d["name"] for d in docs if eval_query(d, flt)]
    actual = {
        "$eq": q({"age": {"$eq": 25}}),
        "$ne": q({"age": {"$ne": 25}}),
        "$gt": q({"age": {"$gt": 25}}),
        "$gte": q({"age": {"$gte": 25}}),
        "$lt": q({"age": {"$lt": 25}}),
        "$lte": q({"age": {"$lte": 25}}),
        "$in": q({"age": {"$in": [20, 25, 30]}}),
        "$nin": q({"age": {"$nin": [20, 25, 30]}}),
    }
    expected = {
        "$eq": ["u3"],
        "$ne": ["u1", "u2", "u4", "u5"],
        "$gt": ["u4", "u5"],
        "$gte": ["u3", "u4", "u5"],
        "$lt": ["u1", "u2"],
        "$lte": ["u1", "u2", "u3"],
        "$in": ["u2", "u3", "u4"],
        "$nin": ["u1", "u5"],
    }
    return {
        "name": "comparison_operators_all_eight",
        "summary": "逐一验证 $eq/$ne/$gt/$gte/$lt/$lte/$in/$nin 全部 8 个比较操作符。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_logical_operators_all_four():
    docs = [
        {"name": "a", "age": 16, "city": "Boston"},
        {"name": "b", "age": 22, "city": "New York"},
        {"name": "c", "age": 30, "city": "New York"},
        {"name": "d", "age": 40, "city": "Chicago"},
        {"name": "e", "city": "Miami"},  # missing age: matches $not:{$gt:25}!
    ]
    q = lambda flt: [d["name"] for d in docs if eval_query(d, flt)]
    actual = {
        "$and": q({"$and": [{"age": {"$gt": 25}}, {"age": {"$lt": 35}}]}),
        "$or": q({"$or": [{"age": {"$gt": 25}}, {"age": {"$lt": 18}}]}),
        "$not": q({"age": {"$not": {"$gt": 25}}}),
        "$nor": q({"$nor": [{"age": {"$gt": 25}}, {"age": {"$lt": 18}}]}),
    }
    expected = {
        "$and": ["c"],
        "$or": ["a", "c", "d"],
        "$not": ["a", "b", "e"],
        "$nor": ["b", "e"],
    }
    return {
        "name": "logical_operators_all_four",
        "summary": "验证 $and/$or/$not/$nor 四个逻辑操作符(含 $not 匹配缺失字段的 MongoDB 特性)。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_element_operators_exists_and_type():
    docs = [
        {"id": 1, "age": 25},
        {"id": 2, "age": "25"},
        {"id": 3, "age": None},
        {"id": 4, "name": "no_age"},
    ]
    actual = {
        "exists_true": [d["id"] for d in docs if eval_query(d, {"age": {"$exists": True}})],
        "exists_false": [d["id"] for d in docs if eval_query(d, {"age": {"$exists": False}})],
        "type_int": [d["id"] for d in docs if eval_query(d, {"age": {"$type": "int"}})],
    }
    expected = {
        "exists_true": [1, 2, 3],
        "exists_false": [4],
        "type_int": [1],
    }
    return {
        "name": "element_operators_exists_and_type",
        "summary": "验证 $exists(区分显式 null 与字段缺失)及 $type 精确匹配 BSON 整型字段。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_array_operators_all_elemmatch_size():
    docs = [
        {
            "id": 1,
            "tags": ["red", "blue", "green"],
            "results": [{"score": 82}],
            "items": [{"quantity": 12}],
        },
        {
            "id": 2,
            "tags": ["red", "yellow"],
            "results": [{"score": 75}, {"score": 90}],  # neither single element is in (80,85)
            "items": [{"quantity": 5}],
        },
        {
            "id": 3,
            "tags": ["mongodb", "database", "nosql"],
            "results": [{"score": 84}],
            "items": [{"quantity": 20}],
        },
    ]
    actual = {
        "all_red_blue": [d["id"] for d in docs if eval_query(d, {"tags": {"$all": ["red", "blue"]}})],
        "all_mongo_db": [d["id"] for d in docs if eval_query(d, {"tags": {"$all": ["mongodb", "database"]}})],
        "elemMatch_score_80_85": [
            d["id"] for d in docs if eval_query(d, {"results": {"$elemMatch": {"score": {"$gt": 80, "$lt": 85}}}})
        ],
        "elemMatch_qty_gt10": [
            d["id"] for d in docs if eval_query(d, {"items": {"$elemMatch": {"quantity": {"$gt": 10}}}})
        ],
        "size_3": [d["id"] for d in docs if eval_query(d, {"tags": {"$size": 3}})],
    }
    expected = {
        "all_red_blue": [1],
        "all_mongo_db": [3],
        "elemMatch_score_80_85": [1, 3],
        "elemMatch_qty_gt10": [1, 3],
        "size_3": [1, 3],
    }
    return {
        "name": "array_operators_all_elemmatch_size",
        "summary": "验证 $all、$elemMatch(要求单个数组元素同时满足复合条件)与 $size 长度过滤。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_regex_text_geo_and_where_operators():
    people = [
        {"name": "John Doe", "bio": "Loves artisan coffee beans", "age": 30, "location": [10.002, 20.001]},
        {"name": "Alice Wu", "bio": "Prefers green tea", "age": 22, "location": [10.5, 20.5]},
    ]
    regex_hits = [p["name"] for p in people if eval_query(p, {"name": {"$regex": r"^John"}})]
    text_hits = [p["name"] for p in people if "coffee" in re.findall(r"[a-z]+", p["bio"].lower())]
    near_hits = [
        p["name"]
        for p in people
        if haversine_meters(10.0, 20.0, p["location"][0], p["location"][1]) <= 1000.0
    ]
    # $geoWithin $centerSphere radius in radians (1 radian ~= 6371 km)
    within_sphere = [
        p["name"]
        for p in people
        if (haversine_meters(10.0, 20.0, p["location"][0], p["location"][1]) / 6371000.0) <= 1.0
    ]
    # Equivalent of $where "this.age > 25" without unsafe eval
    where_equiv = [p["name"] for p in people if p["age"] > 25]

    actual = {
        "$regex": regex_hits,
        "$text": text_hits,
        "$near_1000m": near_hits,
        "$geoWithin_1rad": within_sphere,
        "$where_equiv_age_gt25": where_equiv,
    }
    expected = {
        "$regex": ["John Doe"],
        "$text": ["John Doe"],
        "$near_1000m": ["John Doe"],
        "$geoWithin_1rad": ["John Doe", "Alice Wu"],
        "$where_equiv_age_gt25": ["John Doe"],
    }
    return {
        "name": "regex_text_geo_and_where_operators",
        "summary": "验证 $regex、词元化 $text、球面距离 $near/$geoWithin 与 $where 等价过滤语义。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_comparison_operators_all_eight(),
        case_logical_operators_all_four(),
        case_element_operators_exists_and_type(),
        case_array_operators_all_elemmatch_size(),
        case_regex_text_geo_and_where_operators(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
验证 8 个比较符、4 个逻辑符(含 $not 缺失字段)、$exists/$type、$all/$elemMatch/$size 及正则/文本/球面地理查询。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:MongoDB

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

下载课程关联工程包:MongoDB

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

不会命中;`$elemMatch` 要求数组中的**同一个元素**同时满足 `> 80` 且 `< 85`,而 `75` 与 `90` 均不落在该区间内。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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