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

离线验证 DBRef ($ref/$id/$db) 显式跨库解析与多集合动态路由

PYTHONWindows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。explore-database-references.py
explore-database-references.py113 行
"""Offline MongoDB Manual Reference vs DBRef multi-collection resolution verifier."""
import json

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


def resolve_dbref(databases, default_db, dbref):
    target_db = dbref.get("$db", default_db)
    target_col = dbref["$ref"]
    target_id = dbref["$id"]
    for doc in databases.get(target_db, {}).get(target_col, []):
        if doc["_id"] == target_id:
            return dict(doc)
    return None


def main():
    databases = {
        "appdb": {
            "users": [
                {
                    "_id": "53402597d852426020000002",
                    "name": "Tom Benzamin",
                    "contact": "987654321",
                    "dob": "01-01-1991",
                    "address": {
                        "$ref": "address_home",
                        "$id": "534009e4d852427820000002",
                        "$db": "appdb",
                    },
                },
                {
                    "_id": "53402597d852426020000003",
                    "name": "Lisa Chen",
                    "address": {
                        "$ref": "address_office",
                        "$id": "534009e4d852427820000009",
                    },
                },
            ],
            "address_home": [
                {
                    "_id": "534009e4d852427820000002",
                    "building": "22 A, Indiana Apt",
                    "pincode": 123456,
                    "city": "Los Angeles",
                    "state": "California",
                }
            ],
            "address_office": [
                {
                    "_id": "534009e4d852427820000009",
                    "building": "500 Tech Plaza",
                    "pincode": 94107,
                    "city": "San Francisco",
                    "state": "California",
                }
            ],
        }
    }

    # Case 1: DBRef structure & cross-collection resolution with explicit $db
    tom = databases["appdb"]["users"][0]
    tom_addr = resolve_dbref(databases, "appdb", tom["address"])
    c1_actual = {
        "dbref_fields": sorted(tom["address"].keys()),
        "resolved_city": tom_addr["city"],
        "resolved_building": tom_addr["building"],
        "resolved_pincode": tom_addr["pincode"],
    }
    c1_expected = {
        "dbref_fields": ["$db", "$id", "$ref"],
        "resolved_city": "Los Angeles",
        "resolved_building": "22 A, Indiana Apt",
        "resolved_pincode": 123456,
    }

    # Case 2: Optional $db defaults to current database across polymorphic collections
    lisa = databases["appdb"]["users"][1]
    lisa_addr = resolve_dbref(databases, "appdb", lisa["address"])
    c2_actual = {
        "has_explicit_db": "$db" in lisa["address"],
        "ref_collection": lisa["address"]["$ref"],
        "resolved_city": lisa_addr["city"],
    }
    c2_expected = {
        "has_explicit_db": False,
        "ref_collection": "address_office",
        "resolved_city": "San Francisco",
    }

    cases = [
        {
            "name": "dbref_explicit_db_resolution",
            "summary": "Verify DBRef ($ref, $id, $db) resolves Tom Benzamin's document from address_home.",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "dbref_polymorphic_default_db",
            "summary": "Verify DBRef omitting optional $db resolves dynamically across multiple address collections.",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

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

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-database-references.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:MongoDB

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

下载课程关联工程包:MongoDB

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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