蓝色天空.知识 · 实践 · 创造
我的收藏
MongoDB 教程目录 49章
MongoDB / LEARN BY DOING

MongoDB 更新文档

系统解析 MongoDB 现代更新家族(updateOne、updateMany、replaceOne、findOneAndUpdate)、upsert/arrayFilters/collation/returnDocument 选项以及历史 update()/save() 标志映射。

学完这一章,你能够

  • 系统解析 MongoDB 现代更新家族(updateOne、updateMany、replaceOne、findOneAndUpdate)、upsert/arrayFilters/collation/returnDocument 选项以及历史 update()/save() 标志映射。

现代四大更新接口:updateOne、updateMany、replaceOne、findOneAndUpdate

现代 MongoDB 提供四个语义清晰的核心更新方法:`updateOne(filter, update, options)` 仅修改匹配 `filter` 的第一条文档(例如 `{ name: "Alice" }` 配合 `{ $set: { age: 26 } }`);`updateMany(filter, update, options)` 修改所有命中 `filter` 的文档(例如将所有 `age < 30` 的记录设置 `status: "active"`)。两者均要求 `update` 使用 `$set`、`$inc` 等更新操作符(或聚合更新管道),从而精准修改指定字段而不丢失未提及字段。

若需要用一份完整新文档覆盖旧文档,应调用 `replaceOne(filter, replacement, options)`:新文档中不得包含 `$` 更新操作符,替换时自动保留原 `_id`,而新文档中未列出的旧字段将被全部移除。若业务需要“原子查找、更新并立即拿回文档内容”,则使用 `findOneAndUpdate(filter, update, options)`,支持通过 `projection`、`sort`、`upsert` 及 `returnDocument`(`"before"` 或 `"after"`)精确控制返回旧值或新值。

常用更新选项与典型用法对比

上述接口的 `options` 常见配置包括:`upsert`(默认 `false`;设为 `true` 时若无匹配文档则合并等值过滤条件与更新内容自动插入新文档);`arrayFilters`(更新嵌套数组时通过标识符精准限定只改满足条件的数组元素);`collation`(定义字符串比较语言与大小写敏感规则);以及专用于 `findOneAndUpdate` 的 `returnDocument`(指定返回更新前 `"before"` 或更新后 `"after"` 的快照,取代旧版 `returnNewDocument` 布尔选项)。

历史 save() 与 update() 位置参数现代对照

在旧版教程或遗留脚本中常见 `db.col.save({ _id: ObjectId(...), ... })` 整文档替换(更新后以 `find().pretty()` 查看)以及四参位置写法 `db.col.update(filter, update, upsert, multi)`:其中 `(false, false)` 对应 `updateOne`、`(false, true)` 对应 `updateMany`、`(true, false)` 对应 `updateOne(..., { upsert: true })`、`(true, true)` 对应 `updateMany(..., { upsert: true })`,配合 `$inc: { count: 1 }` 可对数值字段执行原子自增。MongoDB 4.2+ 与 `mongosh` 已将 `save()` 和旧 `update()` 标记弃用,新代码应统一使用明确的 `updateOne`/`updateMany`/`replaceOne` 方法。

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

含完整源码 · 243 行
展开查看收起
python
"""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()
验证 $set/$inc 计数、replaceOne 删去省略字段、returnDocument before/after、upsert 插入与旧四参等价映射。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1732.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:MongoDB

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

下载课程关联工程包:MongoDB

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

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

`updateOne` 配合 `$set` 仅更新 `age` 并保留 `city: "Shanghai"`;`replaceOne` 会保留 `_id: 1` 但用新文档完全覆盖原内容,因此 `city` 字段会消失。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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