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

运行 21 项 BSON $type 编码表、单/多类型过滤及异构集合字符串标题筛选验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-operators-type.py
explore-operators-type.py220 行
"""Offline MongoDB $type BSON type codes & aliases verifier (Ch21 operators-type)."""
import datetime
import json
import re

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

BSON_TYPE_TABLE = [
    (1, "double"),
    (2, "string"),
    (3, "object"),
    (4, "array"),
    (5, "binData"),
    (6, "undefined"),
    (7, "objectId"),
    (8, "bool"),
    (9, "date"),
    (10, "null"),
    (11, "regex"),
    (12, "dbPointer"),
    (13, "javascript"),
    (14, "symbol"),
    (15, "javascriptWithScope"),
    (16, "int"),
    (17, "timestamp"),
    (18, "long"),
    (19, "decimal"),
    (255, "minKey"),
    (127, "maxKey"),
]

CODE_TO_ALIAS = dict(BSON_TYPE_TABLE)
CODE_TO_ALIAS[-1] = "minKey"  # Signed BSON code equivalent to unsigned 255
ALIAS_TO_CODE = {alias: code for code, alias in BSON_TYPE_TABLE}


class BsonObjectId(str):
    pass


def detect_bson_type(val) -> str:
    if isinstance(val, BsonObjectId):
        return "objectId"
    if isinstance(val, bool):
        return "bool"
    if isinstance(val, int):
        return "int" if -(2**31) <= val <= (2**31 - 1) else "long"
    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 isinstance(val, bytes):
        return "binData"
    if isinstance(val, datetime.datetime):
        return "date"
    if isinstance(val, re.Pattern):
        return "regex"
    if val is None:
        return "null"
    return "unknown"


def normalize_type_spec(spec) -> set[str]:
    items = spec if isinstance(spec, list) else [spec]
    out = set()
    for it in items:
        if isinstance(it, int):
            out.add(CODE_TO_ALIAS[it])
        else:
            out.add(it)
    return out


def match_type(doc: dict, field: str, spec) -> bool:
    if field not in doc:
        return False
    allowed = normalize_type_spec(spec)
    return detect_bson_type(doc[field]) in allowed


def case_bson_type_catalog_21_codes():
    actual = {
        "table_entries": len(BSON_TYPE_TABLE),
        "code_2_is": CODE_TO_ALIAS[2],
        "code_16_is": CODE_TO_ALIAS[16],
        "minKey_signed_and_unsigned": [CODE_TO_ALIAS[-1], CODE_TO_ALIAS[255]],
        "maxKey_code": ALIAS_TO_CODE["maxKey"],
    }
    expected = {
        "table_entries": 21,
        "code_2_is": "string",
        "code_16_is": "int",
        "minKey_signed_and_unsigned": ["minKey", "minKey"],
        "maxKey_code": 127,
    }
    return {
        "name": "bson_type_catalog_21_codes",
        "summary": "核对全部 21 项 BSON 类型代码与字符串别名映射(含 minKey 255/-1 符号位差异说明)。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_single_type_code_and_alias_queries():
    docs = [
        {"id": 1, "fieldName": "hello", "age": 25, "isActive": True, "createdAt": datetime.datetime(2026, 1, 1)},
        {"id": 2, "fieldName": 123, "age": "25", "isActive": 1, "createdAt": "2026-01-01"},
        {"id": 3, "fieldName": None, "age": True, "isActive": False, "createdAt": datetime.datetime(2026, 6, 1)},
    ]
    actual = {
        "string_eq_code2": [d["id"] for d in docs if match_type(d, "fieldName", "string")]
        == [d["id"] for d in docs if match_type(d, "fieldName", 2)],
        "string_ids": [d["id"] for d in docs if match_type(d, "fieldName", 2)],
        "int_excludes_bool": [d["id"] for d in docs if match_type(d, "age", "int")]
        == [d["id"] for d in docs if match_type(d, "age", 16)]
        and [d["id"] for d in docs if match_type(d, "age", 16)] == [1],
        "bool_ids": [d["id"] for d in docs if match_type(d, "isActive", 8)],
        "date_ids": [d["id"] for d in docs if match_type(d, "createdAt", "date")],
    }
    expected = {
        "string_eq_code2": True,
        "string_ids": [1],
        "int_excludes_bool": True,
        "bool_ids": [1, 3],
        "date_ids": [1, 3],
    }
    return {
        "name": "single_type_code_and_alias_queries",
        "summary": "验证 string(2)、int(16)、bool(8)、date(9) 字符串别名与数字代码等价,并严格区分 bool 与 int。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_multi_type_array_and_and_combination():
    docs = [
        {"id": 1, "value": "text", "details": {"k": 1}, "score": 95.5},
        {"id": 2, "value": 42, "details": {"k": 2}, "score": 90},  # int, not double
        {"id": 3, "value": 3.14, "details": ["not_obj"], "score": 88.5},
    ]
    by_alias = [d["id"] for d in docs if match_type(d, "value", ["string", "int"])]
    by_code = [d["id"] for d in docs if match_type(d, "value", [2, 16])]
    and_alias = [
        d["id"]
        for d in docs
        if match_type(d, "details", "object") and match_type(d, "score", "double")
    ]
    and_code = [
        d["id"]
        for d in docs
        if match_type(d, "details", 3) and match_type(d, "score", 1)
    ]
    actual = {
        "multi_type_ids": by_alias,
        "multi_type_matches_codes": by_alias == by_code,
        "and_object_double_ids": and_alias,
        "and_matches_codes": and_alias == and_code,
    }
    expected = {
        "multi_type_ids": [1, 2],
        "multi_type_matches_codes": True,
        "and_object_double_ids": [1],
        "and_matches_codes": True,
    }
    return {
        "name": "multi_type_array_and_and_combination",
        "summary": "验证 $type 数组多类型匹配(string/int 与 [2, 16])以及 $and 联合检查 object(3) 与 double(1)。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_tutorial_col_string_title_filter():
    col = [
        {"_id": BsonObjectId("56066542ade2f21f36b0313a"), "title": "PHP 教程", "likes": 200},
        {"_id": BsonObjectId("56066549ade2f21f36b0313b"), "title": "Java 教程", "likes": 150},
        {"_id": BsonObjectId("5606654fade2f21f36b0313c"), "title": "MongoDB 教程", "likes": 100},
        {"_id": BsonObjectId("5606654fade2f21f36b0313d"), "title": 404, "likes": 0},
    ]
    matched_code = [d["title"] for d in col if match_type(d, "title", 2)]
    matched_name = [d["title"] for d in col if match_type(d, "title", "string")]
    actual = {
        "titles_by_code2": matched_code,
        "equal_to_string_alias": matched_code == matched_name,
        "oid_detected": detect_bson_type(col[0]["_id"]),
    }
    expected = {
        "titles_by_code2": ["PHP 教程", "Java 教程", "MongoDB 教程"],
        "equal_to_string_alias": True,
        "oid_detected": "objectId",
    }
    return {
        "name": "tutorial_col_string_title_filter",
        "summary": "验证在混合类型集合中按 title: {$type: 2} 与 {$type: 'string'} 仅筛出 3 条字符串标题文档。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_bson_type_catalog_21_codes(),
        case_single_type_code_and_alias_queries(),
        case_multi_type_array_and_and_combination(),
        case_tutorial_col_string_title_filter(),
    ]
    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-type-lab/explore-operators-type.py

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

下载课程关联工程包:MongoDB

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

下载课程关联工程包:MongoDB

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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