蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-operators.py
explore-operators.py307 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/mongodb-operators-lab/explore-operators.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-operators.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:MongoDB

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

下载课程关联工程包:MongoDB

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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