"""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()
本例需在 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。
入口文件:projects/mongodb-capped-collections-lab/explore-capped-collections.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-capped-collections.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1734.zip
课程关联工程包(登记关联49章) · 含当前章节或实例 · mbskycom202612a1732.zip