蓝色天空网mbsky.com · 知识 · 实践 · 创造MongoDB · 本地阅读预览
教程 / 数据库 / MongoDB

MongoDB 固定集合

系统梳理 MongoDB 固定集合(Capped Collections)的环形缓冲区原理、创建与 convertToCapped 转换命令、$natural 自然顺序查询及禁止单条删除/禁止扩容更新约束,并在离线环形集合中完成 FIFO 淘汰实测。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

固定集合环形队列机制、创建与转换

MongoDB 固定集合(Capped Collections)是一种预先限定最大字节容量(并可选限定最大文档数)的高性能集合,其内部行为类似先进先出(FIFO)的环形队列:当集合空间或文档数触及上限后,继续插入的新文档会自动覆盖淘汰最早写入的头部文档,无需后台定期执行删除任务。

创建固定集合必须通过 `db.createCollection("cappedLogCollection", {capped: true, size: 10000})` 显式声明 `capped: true` 与字节上限 `size`(必填),还可附加 `max: 1000` 同时约束最大文档条数(实际运行中字节数与文档数任一条件先触达都会触发淘汰)。通过 `db.cappedLogCollection.isCapped()` 可判断集合是否为固定集合;若需把既有普通集合转为固定集合,可执行 `db.runCommand({convertToCapped: "posts", size: 10000})`。

自然顺序查询、写操作约束与适用场景

固定集合严格按插入物理顺序存储文档,默认查询即按插入顺序返回,配合 `db.cappedLogCollection.find().sort({$natural: -1})` 可以极低开销反向读取最新写入的记录。为维持连续顺序布局,固定集合对修改操作施加了严格约束:允许插入与不超出原文档大小的就地更新(文档体积一旦增长更新就会失败),**不允许删除单条文档**;若需清空全部数据只能调用 `drop()` 销毁集合并显式重新创建。此外,历史 32 位系统上单个固定集合容量受限于约 482.5MB,在现代 64 位系统上则仅受文件系统与可用磁盘空间制约。

综合来看,固定集合具备三大核心属性——顺序插入速度极快、按插入顺序扫描输出极快、写入新数据时自动淘汰最旧数据——因此特别适合两类典型场景:一是高频滚动记录应用/审计日志(配合 Tailable Cursor 可实现轻量级消息流订阅),二是缓存少量近期热文档(例如系统最近 N 条操作记录)。离线环形集合验证器已实测 `max=3` 与字节上限下的 FIFO 自动淘汰、`$natural: -1` 倒序读取,以及扩容更新与单条删除被拒绝的完整语义。

离线验证固定集合 max/size FIFO 淘汰、$natural:-1 倒序读取与更新/删除约束

python · 阅读源码
"""Offline MongoDB Capped Collection FIFO eviction, $natural sort & mutation constraints verifier."""
import json

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


class CappedCollection:
    def __init__(self, name, max_size_bytes, max_docs=None):
        self.name = name
        self.capped = True
        self.max_size_bytes = max_size_bytes
        self.max_docs = max_docs
        self._docs = []

    @staticmethod
    def doc_size(doc):
        return len(json.dumps(doc, ensure_ascii=False).encode("utf-8"))

    def total_bytes(self):
        return sum(self.doc_size(d) for d in self._docs)

    def insert(self, doc):
        row = dict(doc)
        self._docs.append(row)
        while (self.max_docs is not None and len(self._docs) > self.max_docs) or (
            self.total_bytes() > self.max_size_bytes and len(self._docs) > 1
        ):
            self._docs.pop(0)

    def find_natural(self, direction=1):
        if direction == -1:
            return [dict(d) for d in reversed(self._docs)]
        return [dict(d) for d in self._docs]

    def update_in_place(self, doc_id, new_fields):
        for idx, d in enumerate(self._docs):
            if d["_id"] == doc_id:
                old_sz = self.doc_size(d)
                candidate = dict(d)
                candidate.update(new_fields)
                if self.doc_size(candidate) > old_sz:
                    return {"ok": False, "error": "capped_document_growth_not_allowed"}
                self._docs[idx] = candidate
                return {"ok": True}
        return {"ok": False, "error": "not_found"}

    def delete_one(self):
        return {"ok": False, "error": "cannot_delete_from_capped_collection"}


def main():
    # Case 1: Creation with capped=True, size & max, FIFO ring-buffer eviction, and $natural: -1 sort
    logs = CappedCollection("cappedLogCollection", max_size_bytes=10000, max_docs=3)
    for i in range(1, 6):
        logs.insert({"_id": i, "msg": f"evt-{i}"})
    asc_ids = [d["_id"] for d in logs.find_natural(1)]
    desc_ids = [d["_id"] for d in logs.find_natural(-1)]
    c1_actual = {
        "is_capped": logs.capped,
        "natural_asc_ids": asc_ids,
        "natural_desc_ids": desc_ids,
    }
    c1_expected = {
        "is_capped": True,
        "natural_asc_ids": [3, 4, 5],
        "natural_desc_ids": [5, 4, 3],
    }

    # Case 2: Byte-size eviction, convertToCapped, and prohibited delete / growing-update
    byte_cap = CappedCollection("posts", max_size_bytes=100)
    for i in range(1, 5):
        byte_cap.insert({"_id": i, "msg": f"log-entry-{i}"})
    kept_after_bytes = [d["_id"] for d in byte_cap.find_natural(1)]
    same_size_upd = byte_cap.update_in_place(kept_after_bytes[-1], {"msg": "log-fixed-4"})
    grow_upd = byte_cap.update_in_place(kept_after_bytes[-1], {"msg": "much-longer-payload-exceeding-original-doc-size"})
    del_attempt = byte_cap.delete_one()
    c2_actual = {
        "byte_evicted_kept_ids": kept_after_bytes,
        "same_size_update_ok": same_size_upd["ok"],
        "growing_update_ok": grow_upd["ok"],
        "delete_one_ok": del_attempt["ok"],
    }
    c2_expected = {
        "byte_evicted_kept_ids": [2, 3, 4],
        "same_size_update_ok": True,
        "growing_update_ok": False,
        "delete_one_ok": False,
    }

    cases = [
        {
            "name": "capped_collection_fifo_and_natural_sort",
            "summary": "Verify capped collection evicts oldest docs when max=3 is exceeded and supports $natural: -1 reverse scan.",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "capped_size_eviction_and_mutation_rules",
            "summary": "Verify byte-size eviction, in-place same-size update success, growing-update rejection, and delete rejection.",
            "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()
预期结果 · 待实际运行核验
  • 在离线固定集合中确认超过 max=3 时自动淘汰最旧文档保留 [3,4,5]、$natural:-1 返回 [5,4,3]、字节上限淘汰、等长更新成功而扩容更新与 deleteOne 均被拒绝。
离线验证固定集合 max/size FIFO 淘汰、$natural:-1 倒序读取与更新/删除约束

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

当前源码 SHA256:8dfa472195ad0d5d13ab015d0118dedd37cfb1ce9e2f6e82b2cc64b74555a6db

下载本站示例源码

本地运行

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

下载MongoDB 固定集合实验

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

ZIP SHA256:b0dadd92d614e63798ee737a50d0936ba45e5b46e840143e196a3a4b2441bb30

常见错误与边界

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

练习与解答

在固定集合中如果同时设置了 size: 10000 和 max: 1000,什么时候会开始淘汰旧文档?

展开参考解答

size 与 max 两个上限中任意一个先达到时就会立即按 FIFO 顺序淘汰最早写入的文档(size 始终是必填项且优先级生效,即使文档数不足 1000,只要总字节达到 size 也会开始覆盖旧文档)。

规范与官方依据