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

离线验证 Node.js MongoClient URI、async/await CRUD、排序分页与 $lookup 左连接

PYTHONWindows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。explore-nodejs-mongodb.py
explore-nodejs-mongodb.py236 行
"""Offline Node.js MongoDB Driver async/await CRUD, pagination & $lookup verifier."""
import json
from urllib.parse import urlparse

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


class MockNodeCollection:
    def __init__(self, name):
        self.name = name
        self.docs = []
        self._seq = 1

    def insert_one(self, doc):
        row = dict(doc)
        row.setdefault("_id", f"6678e1d1f9503dc2e0e2a{self._seq:03x}")
        self._seq += 1
        self.docs.append(row)
        return {"insertedId": row["_id"]}

    def insert_many(self, docs):
        ids = {}
        for idx, d in enumerate(docs):
            res = self.insert_one(d)
            ids[idx] = res["insertedId"]
        return {"insertedCount": len(docs), "insertedIds": ids}

    def find(self, flt=None, projection=None, sort=None, skip=0, limit=None):
        flt = flt or {}
        rows = [dict(d) for d in self.docs if all(d.get(k) == v for k, v in flt.items())]
        if sort:
            for k, direction in reversed(list(sort.items())):
                rows.sort(key=lambda x, f=k: x.get(f), reverse=(direction == -1))
        if skip:
            rows = rows[skip:]
        if limit is not None:
            rows = rows[:limit]
        if projection:
            include_id = projection.get("_id", 1) != 0
            projected = []
            for r in rows:
                item = {}
                if include_id and "_id" in r:
                    item["_id"] = r["_id"]
                for k, v in projection.items():
                    if k != "_id" and v == 1 and k in r:
                        item[k] = r[k]
                projected.append(item)
            rows = projected
        return rows

    def update_one(self, flt, upd):
        for d in self.docs:
            if all(d.get(k) == v for k, v in flt.items()):
                d.update(upd.get("$set", {}))
                return {"matchedCount": 1, "modifiedCount": 1}
        return {"matchedCount": 0, "modifiedCount": 0}

    def update_many(self, flt, upd):
        matched = 0
        for d in self.docs:
            if all(d.get(k) == v for k, v in flt.items()):
                d.update(upd.get("$set", {}))
                matched += 1
        return {"matchedCount": matched, "modifiedCount": matched}

    def delete_one(self, flt):
        for idx, d in enumerate(self.docs):
            if all(d.get(k) == v for k, v in flt.items()):
                self.docs.pop(idx)
                return {"deletedCount": 1}
        return {"deletedCount": 0}

    def delete_many(self, flt):
        before = len(self.docs)
        self.docs = [d for d in self.docs if not all(d.get(k) == v for k, v in flt.items())]
        return {"deletedCount": before - len(self.docs)}


def lookup_join(left_docs, right_docs, local_field, foreign_field, as_field):
    right_index = {}
    for rd in right_docs:
        right_index.setdefault(rd[foreign_field], []).append(dict(rd))
    out = []
    for ld in left_docs:
        merged = dict(ld)
        merged[as_field] = list(right_index.get(ld.get(local_field), []))
        out.append(merged)
    return out


def main():
    # Case 1: URI parsing & database/collection creation
    uri = "mongodb://localhost:27017/demo_app?retryWrites=true"
    parsed = urlparse(uri)
    col = MockNodeCollection("exampleCollection")
    r_one = col.insert_one({"name": "Example", "type": "Test"})
    c1_actual = {
        "scheme": parsed.scheme,
        "host": parsed.hostname,
        "port": parsed.port,
        "db": parsed.path.lstrip("/"),
        "inserted_id_len": len(r_one["insertedId"]),
        "driver_v4_plus_deprecated_opts": ["useNewUrlParser", "useUnifiedTopology"],
    }
    c1_expected = {
        "scheme": "mongodb",
        "host": "localhost",
        "port": 27017,
        "db": "demo_app",
        "inserted_id_len": 24,
        "driver_v4_plus_deprecated_opts": ["useNewUrlParser", "useUnifiedTopology"],
    }

    # Case 2: insertMany, find with projection & filter, updateOne, updateMany, deleteOne, deleteMany
    crud = MockNodeCollection("users")
    ins = crud.insert_many([
        {"name": "Alice", "age": 25, "address": "Wonderland"},
        {"name": "Bob", "age": 30, "address": "Builderland"},
        {"name": "Alice", "age": 28, "address": "Old Wonderland"},
        {"name": "Charlie", "age": 35, "address": "Chocolate Factory"},
    ])
    found_alice = crud.find({"name": "Alice"}, projection={"_id": 0, "name": 1, "age": 1})
    u1 = crud.update_one({"name": "Alice"}, {"$set": {"age": 26, "address": "New Wonderland"}})
    um = crud.update_many({"name": "Alice"}, {"$set": {"address": "Updated Wonderland"}})
    d1 = crud.delete_one({"name": "Bob"})
    dm = crud.delete_many({"name": "Alice"})
    remaining_names = [d["name"] for d in crud.find({}, projection={"_id": 0, "name": 1})]
    c2_actual = {
        "inserted_count": ins["insertedCount"],
        "alice_initial_ages": [d["age"] for d in found_alice],
        "update_one_modified": u1["modifiedCount"],
        "update_many_modified": um["modifiedCount"],
        "delete_one_count": d1["deletedCount"],
        "delete_many_count": dm["deletedCount"],
        "remaining_names": remaining_names,
    }
    c2_expected = {
        "inserted_count": 4,
        "alice_initial_ages": [25, 28],
        "update_one_modified": 1,
        "update_many_modified": 2,
        "delete_one_count": 1,
        "delete_many_count": 2,
        "remaining_names": ["Charlie"],
    }

    # Case 3: sort({age: 1 / -1}), limit(3), skip(2)
    page_col = MockNodeCollection("people")
    page_col.insert_many([
        {"name": "Alice", "age": 25},
        {"name": "Bob", "age": 30},
        {"name": "Charlie", "age": 35},
        {"name": "Dave", "age": 20},
        {"name": "Eve", "age": 22},
    ])
    asc_names = [d["name"] for d in page_col.find(sort={"age": 1})]
    desc_names = [d["name"] for d in page_col.find(sort={"age": -1})]
    lim3 = [d["name"] for d in page_col.find(limit=3)]
    skip2 = [d["name"] for d in page_col.find(skip=2)]
    c3_actual = {"asc": asc_names, "desc": desc_names, "limit3": lim3, "skip2": skip2}
    c3_expected = {
        "asc": ["Dave", "Eve", "Alice", "Bob", "Charlie"],
        "desc": ["Charlie", "Bob", "Alice", "Eve", "Dave"],
        "limit3": ["Alice", "Bob", "Charlie"],
        "skip2": ["Charlie", "Dave", "Eve"],
    }

    # Case 4: $lookup left outer join (orders -> products), collection drop & Promise CRUD cycle
    orders = [
        {"_id": 1, "product_id": 101, "quantity": 2},
        {"_id": 2, "product_id": 102, "quantity": 1},
        {"_id": 3, "product_id": 103, "quantity": 4},
    ]
    products = [
        {"_id": 101, "name": "Product A", "price": 50},
        {"_id": 102, "name": "Product B", "price": 70},
        {"_id": 103, "name": "Product C", "price": 100},
        {"_id": 104, "name": "Product D", "price": 120},
    ]
    joined = lookup_join(orders, products, "product_id", "_id", "productDetails")
    # Simulate sequential Promise CRUD lifecycle: insert -> find -> update -> delete -> drop
    lifecycle = MockNodeCollection("documents")
    lid = lifecycle.insert_one({"name": "Document 1"})["insertedId"]
    after_ins = [d["name"] for d in lifecycle.find()]
    lifecycle.update_one({"_id": lid}, {"$set": {"name": "Updated Document 1"}})
    after_upd = [d["name"] for d in lifecycle.find()]
    lifecycle.delete_one({"_id": lid})
    after_del = lifecycle.find()
    c4_actual = {
        "lookup_product_names": [row["productDetails"][0]["name"] for row in joined],
        "lookup_total_order_values": [row["quantity"] * row["productDetails"][0]["price"] for row in joined],
        "lifecycle": [after_ins, after_upd, after_del],
    }
    c4_expected = {
        "lookup_product_names": ["Product A", "Product B", "Product C"],
        "lookup_total_order_values": [100, 70, 400],
        "lifecycle": [["Document 1"], ["Updated Document 1"], []],
    }

    cases = [
        {
            "name": "node_connect_uri_and_options",
            "summary": "Verify Node.js MongoClient URI parsing, insertOne ID generation, and v4+ deprecated options note.",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "node_crud_insert_find_update_delete",
            "summary": "Verify insertMany, find with projection, updateOne/updateMany, and deleteOne/deleteMany.",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "node_sort_limit_skip_pagination",
            "summary": "Verify cursor sort ascending/descending, limit(3), and skip(2) pagination behavior.",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
        {
            "name": "node_lookup_drop_and_promise_chain",
            "summary": "Verify $lookup left outer join between orders and products plus sequential Promise CRUD lifecycle.",
            "expected": c4_expected,
            "actual": c4_actual,
            "passed": c4_actual == c4_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-nodejs-mongodb-lab/explore-nodejs-mongodb.py

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

下载课程关联工程包:MongoDB

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

下载课程关联工程包:MongoDB

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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