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

离线验证图书库存防超卖 findOneAndUpdate、九类原子操作符与位置操作符 $

PYTHONWindows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。explore-atomic-operations.py
explore-atomic-operations.py162 行
"""Offline MongoDB single-document atomic findOneAndUpdate & update operators verifier."""
import copy
import json

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


def find_one_and_update(docs, query, update, return_after=True):
    for idx, doc in enumerate(docs):
        matched = True
        for k, cond in query.items():
            val = doc.get(k)
            if isinstance(cond, dict) and "$gt" in cond:
                if not (val is not None and val > cond["$gt"]):
                    matched = False
            elif val != cond:
                matched = False
        if not matched:
            continue
        before = copy.deepcopy(doc)
        if "$inc" in update:
            for fk, delta in update["$inc"].items():
                doc[fk] = doc.get(fk, 0) + delta
        if "$push" in update:
            for fk, item in update["$push"].items():
                doc.setdefault(fk, [])
                if isinstance(item, dict) and "$each" in item:
                    doc[fk].extend(item["$each"])
                else:
                    doc[fk].append(item)
        if "$set" in update:
            for fk, fv in update["$set"].items():
                doc[fk] = fv
        if "$unset" in update:
            for fk in update["$unset"]:
                doc.pop(fk, None)
        if "$pull" in update:
            for fk, val in update["$pull"].items():
                doc[fk] = [x for x in doc.get(fk, []) if x != val]
        if "$addToSet" in update:
            for fk, val in update["$addToSet"].items():
                arr = doc.setdefault(fk, [])
                if val not in arr:
                    arr.append(val)
        if "$pop" in update:
            for fk, direction in update["$pop"].items():
                arr = doc.get(fk, [])
                if arr:
                    arr.pop(-1 if direction == 1 else 0)
        if "$rename" in update:
            for old_k, new_k in update["$rename"].items():
                if old_k in doc:
                    doc[new_k] = doc.pop(old_k)
        if "$bit" in update:
            for fk, ops in update["$bit"].items():
                if "and" in ops:
                    doc[fk] = doc[fk] & ops["and"]
                if "or" in ops:
                    doc[fk] = doc[fk] | ops["or"]
        return copy.deepcopy(doc if return_after else before)
    return None


def main():
    # Case 1: Library book atomic checkout (findOneAndUpdate with available > 0 guard)
    books = [
        {
            "_id": 123456789,
            "title": "MongoDB: The Definitive Guide",
            "available": 2,
            "checkout": [{"by": "joe", "date": "2012-10-15"}],
        }
    ]
    r1 = find_one_and_update(
        books,
        {"_id": 123456789, "available": {"$gt": 0}},
        {"$inc": {"available": -1}, "$push": {"checkout": {"by": "alice", "date": "2026-01-01"}}},
    )
    r2 = find_one_and_update(
        books,
        {"_id": 123456789, "available": {"$gt": 0}},
        {"$inc": {"available": -1}, "$push": {"checkout": {"by": "bob", "date": "2026-01-02"}}},
    )
    # Third attempt must fail atomically because available == 0 (no overselling!)
    r3 = find_one_and_update(
        books,
        {"_id": 123456789, "available": {"$gt": 0}},
        {"$inc": {"available": -1}, "$push": {"checkout": {"by": "charlie", "date": "2026-01-03"}}},
    )
    c1_actual = {
        "after_r1_available": r1["available"],
        "after_r2_available": r2["available"],
        "r3_blocked_when_zero": r3 is None,
        "final_checkout_users": [c["by"] for c in books[0]["checkout"]],
    }
    c1_expected = {
        "after_r1_available": 1,
        "after_r2_available": 0,
        "r3_blocked_when_zero": True,
        "final_checkout_users": ["joe", "alice", "bob"],
    }

    # Case 2: All atomic update operators ($set, $unset, $inc, $push+$each, $pull, $addToSet, $pop, $rename, $bit)
    items = [{"_id": 1, "old_name": "itemA", "count": 10, "tags": ["a"], "flags": 7, "temp": True}]
    find_one_and_update(items, {"_id": 1}, {"$set": {"status": "ready"}, "$unset": {"temp": 1}, "$inc": {"count": 5}})
    find_one_and_update(items, {"_id": 1}, {"$push": {"tags": {"$each": ["b", "c"]}}})
    find_one_and_update(items, {"_id": 1}, {"$addToSet": {"tags": "b"}})  # duplicate ignored
    find_one_and_update(items, {"_id": 1}, {"$pull": {"tags": "a"}})
    find_one_and_update(items, {"_id": 1}, {"$pop": {"tags": 1}})  # remove last ("c")
    find_one_and_update(items, {"_id": 1}, {"$rename": {"old_name": "name"}, "$bit": {"flags": {"and": 5}}})
    c2_actual = items[0]
    c2_expected = {
        "_id": 1,
        "name": "itemA",
        "count": 15,
        "tags": ["b"],
        "flags": 5,
        "status": "ready",
    }

    # Case 3: Positional operator '$' updating matched comment element in array
    post = {
        "_id": "4b97e62bf1d8c7152c9ccb74",
        "title": "ABC",
        "comments": [{"by": "joe", "votes": 3}, {"by": "jane", "votes": 7}],
    }
    for comment in post["comments"]:
        if comment["by"] == "joe":
            comment["votes"] += 1
            break
    c3_actual = {c["by"]: c["votes"] for c in post["comments"]}
    c3_expected = {"joe": 4, "jane": 7}

    cases = [
        {
            "name": "atomic_book_checkout_inventory_guard",
            "summary": "Verify conditional findOneAndUpdate ($gt: 0) with $inc/-1 and $push prevents negative inventory.",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "atomic_update_operators_suite",
            "summary": "Verify $set, $unset, $inc, $push/$each (modern $pushAll replacement), $addToSet, $pull, $pop, $rename, and $bit.",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "positional_operator_array_element_inc",
            "summary": "Verify positional operator 'comments.$.votes' increments only the matched array element.",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_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-atomic-operations-lab/explore-atomic-operations.py

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

下载课程关联工程包:MongoDB

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

下载课程关联工程包:MongoDB

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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