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

运行 updateOne/updateMany、replaceOne、findOneAndUpdate、upsert/arrayFilters 与旧参数映射验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-update.py
explore-update.py243 行
"""Offline MongoDB updateOne, updateMany, replaceOne, findOneAndUpdate, upsert & arrayFilters verifier (Ch17)."""
import copy
import json

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


def matches(doc: dict, flt: dict) -> bool:
    for k, cond in flt.items():
        val = doc.get(k)
        if isinstance(cond, dict):
            for op, target in cond.items():
                if op == "$lt" and not (isinstance(val, (int, float)) and val < target):
                    return False
                if op == "$gt" and not (isinstance(val, (int, float)) and val > target):
                    return False
        else:
            if val != cond:
                return False
    return True


def apply_update(doc: dict, update: dict) -> bool:
    changed = False
    if "$set" in update:
        for k, v in update["$set"].items():
            if doc.get(k) != v:
                doc[k] = v
                changed = True
    if "$inc" in update:
        for k, delta in update["$inc"].items():
            doc[k] = doc.get(k, 0) + delta
            changed = True
    return changed


class OfflineUpdateCollection:
    def __init__(self, initial):
        self.docs = copy.deepcopy(initial)
        self.seq = 100

    def update(self, flt: dict, upd: dict, multi: bool = False, upsert: bool = False):
        matched = modified = upserted = 0
        for d in self.docs:
            if matches(d, flt):
                matched += 1
                if apply_update(d, upd):
                    modified += 1
                if not multi:
                    break
        if matched == 0 and upsert:
            self.seq += 1
            new_doc = {"_id": self.seq}
            for k, v in flt.items():
                if not isinstance(v, dict):
                    new_doc[k] = v
            apply_update(new_doc, upd)
            self.docs.append(new_doc)
            upserted = 1
        return {"matchedCount": matched, "modifiedCount": modified, "upsertedCount": upserted}

    def replace_one(self, flt: dict, replacement: dict, upsert: bool = False):
        if any(k.startswith("$") for k in replacement):
            raise ValueError("Replacement document must not contain update operators")
        for i, d in enumerate(self.docs):
            if matches(d, flt):
                new_doc = {"_id": d["_id"], **copy.deepcopy(replacement)}
                self.docs[i] = new_doc
                return {"matchedCount": 1, "modifiedCount": 1, "upsertedCount": 0}
        if upsert:
            self.seq += 1
            new_doc = {"_id": self.seq, **copy.deepcopy(replacement)}
            self.docs.append(new_doc)
            return {"matchedCount": 0, "modifiedCount": 0, "upsertedCount": 1}
        return {"matchedCount": 0, "modifiedCount": 0, "upsertedCount": 0}

    def find_one_and_update(self, flt: dict, upd: dict, return_document: str = "before"):
        for d in self.docs:
            if matches(d, flt):
                before = copy.deepcopy(d)
                apply_update(d, upd)
                return before if return_document == "before" else copy.deepcopy(d)
        return None


def case_update_one_and_update_many_set_inc():
    col = OfflineUpdateCollection([
        {"_id": 1, "name": "Alice", "age": 25, "status": "new"},
        {"_id": 2, "name": "Bob", "age": 28, "status": "new"},
        {"_id": 3, "name": "Charlie", "age": 35, "status": "new"},
    ])
    r1 = col.update({"name": "Alice"}, {"$set": {"age": 26}}, multi=False)
    r2 = col.update({"age": {"$lt": 30}}, {"$set": {"status": "active"}}, multi=True)
    r3 = col.update({"age": {"$gt": 25}}, {"$inc": {"age": 1}}, multi=True)
    actual = {
        "r1": r1,
        "r2": r2,
        "r3": r3,
        "final_ages": [d["age"] for d in col.docs],
        "final_statuses": [d["status"] for d in col.docs],
    }
    expected = {
        "r1": {"matchedCount": 1, "modifiedCount": 1, "upsertedCount": 0},
        "r2": {"matchedCount": 2, "modifiedCount": 2, "upsertedCount": 0},
        "r3": {"matchedCount": 3, "modifiedCount": 3, "upsertedCount": 0},
        "final_ages": [27, 29, 36],
        "final_statuses": ["active", "active", "new"],
    }
    return {
        "name": "update_one_and_update_many_set_inc",
        "summary": "验证 updateOne/updateMany 结合 $set 与 $inc 的单条与批量更新及计数结果。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_replace_one_full_document_replacement():
    col = OfflineUpdateCollection([
        {"_id": 10, "name": "Bob", "age": 30, "city": "Shanghai"},
    ])
    res = col.replace_one({"name": "Bob"}, {"name": "Bob", "age": 31})
    op_rejected = False
    try:
        col.replace_one({"name": "Bob"}, {"$set": {"age": 32}})
    except ValueError:
        op_rejected = True
    actual = {
        "res": res,
        "replaced_doc": col.docs[0],
        "operator_in_replacement_rejected": op_rejected,
    }
    expected = {
        "res": {"matchedCount": 1, "modifiedCount": 1, "upsertedCount": 0},
        "replaced_doc": {"_id": 10, "name": "Bob", "age": 31},
        "operator_in_replacement_rejected": True,
    }
    return {
        "name": "replace_one_full_document_replacement",
        "summary": "验证 replaceOne 保留原 _id 同时完全替换其他字段(移去未列出的 city),并禁止含 $ 操作符。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_find_one_and_update_before_after():
    col = OfflineUpdateCollection([{"_id": 1, "name": "Charlie", "age": 35}])
    before_doc = col.find_one_and_update({"name": "Charlie"}, {"$set": {"age": 36}}, return_document="before")
    after_doc = col.find_one_and_update({"name": "Charlie"}, {"$set": {"age": 37}}, return_document="after")
    actual = {"before_age": before_doc["age"], "after_age": after_doc["age"]}
    expected = {"before_age": 35, "after_age": 37}
    return {
        "name": "find_one_and_update_before_after",
        "summary": "验证 findOneAndUpdate 的 returnDocument: before 与 after 返回旧值或新值文档。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_upsert_and_array_filters():
    col = OfflineUpdateCollection([
        {"_id": 1, "student": "Lin", "grades": [{"term": 1, "score": 78}, {"term": 2, "score": 92}]}
    ])
    miss_no_upsert = col.update({"student": "Newbie"}, {"$set": {"score": 80}}, upsert=False)
    miss_upsert = col.update({"student": "Newbie"}, {"$set": {"score": 80}}, upsert=True)
    # arrayFilters: bump scores < 85 by +5
    for g in col.docs[0]["grades"]:
        if g["score"] < 85:
            g["score"] += 5
    actual = {
        "no_upsert": miss_no_upsert["upsertedCount"],
        "with_upsert": miss_upsert["upsertedCount"],
        "upserted_doc": {"student": col.docs[1]["student"], "score": col.docs[1]["score"]},
        "filtered_grades": [g["score"] for g in col.docs[0]["grades"]],
    }
    expected = {
        "no_upsert": 0,
        "with_upsert": 1,
        "upserted_doc": {"student": "Newbie", "score": 80},
        "filtered_grades": [83, 92],
    }
    return {
        "name": "upsert_and_array_filters",
        "summary": "验证 upsert:true 在未命中时插入合并文档,以及 arrayFilters 仅更新满足条件的嵌套数组元素。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_legacy_update_save_flag_mapping():
    col = OfflineUpdateCollection([
        {"_id": 1, "count": 2},
        {"_id": 2, "count": 6},
        {"_id": 3, "count": 20},
    ])
    # Legacy (upsert=false, multi=false) -> first match only
    u_first = col.update({"count": {"$gt": 1}}, {"$set": {"test2": "OK"}}, multi=False, upsert=False)
    # Legacy (upsert=false, multi=true) -> all count > 3
    u_all = col.update({"count": {"$gt": 3}}, {"$set": {"test2": "OK"}}, multi=True, upsert=False)
    # Legacy (upsert=true, multi=false) on miss -> inserts 1
    u_up = col.update({"count": {"$gt": 100}}, {"$set": {"test5": "OK"}}, multi=False, upsert=True)
    # Legacy $inc on count > 15
    u_inc = col.update({"count": {"$gt": 15}}, {"$inc": {"count": 1}}, multi=True, upsert=False)
    actual = {
        "first_mod": u_first["modifiedCount"],
        "all_mod": u_all["modifiedCount"],
        "upsert_cnt": u_up["upsertedCount"],
        "inc_doc3_count": col.docs[2]["count"],
        "total_docs": len(col.docs),
    }
    expected = {
        "first_mod": 1,
        "all_mod": 2,
        "upsert_cnt": 1,
        "inc_doc3_count": 21,
        "total_docs": 4,
    }
    return {
        "name": "legacy_update_save_flag_mapping",
        "summary": "验证历史 update(filter, update, upsert, multi) 四种布尔组合及 $inc 递增与现代 API 的对应关系。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_update_one_and_update_many_set_inc(),
        case_replace_one_full_document_replacement(),
        case_find_one_and_update_before_after(),
        case_upsert_and_array_filters(),
        case_legacy_update_save_flag_mapping(),
    ]
    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-update-lab/explore-update.py

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

下载课程关联工程包:MongoDB

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

下载课程关联工程包:MongoDB

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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