"""Offline PHP 7/8 `mongodb` extension (Manager/BulkWrite/Query/WriteConcern) verifier."""
import json
VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"
class MockBulkWrite:
def __init__(self):
self.ops = []
def insert(self, doc):
row = dict(doc)
row.setdefault("_id", f"66000000000000000000{len(self.ops) + 1:04x}")
self.ops.append(("insert", row))
return row["_id"]
def update(self, flt, update_doc, multi=False, upsert=False):
self.ops.append(("update", flt, update_doc, {"multi": multi, "upsert": upsert}))
def delete(self, flt, limit=0):
self.ops.append(("delete", flt, {"limit": limit}))
class MockPhpManager:
def __init__(self, uri):
self.uri = uri
self.namespaces = {}
def execute_bulk_write(self, namespace, bulk, write_concern="majority"):
docs = self.namespaces.setdefault(namespace, [])
stats = {"inserted": 0, "modified": 0, "deleted": 0, "write_concern": write_concern}
for op in bulk.ops:
kind = op[0]
if kind == "insert":
docs.append(dict(op[1]))
stats["inserted"] += 1
elif kind == "update":
_, flt, upd, opts = op
matched = 0
for d in docs:
if all(d.get(k) == v for k, v in flt.items()):
d.update(upd.get("$set", {}))
matched += 1
stats["modified"] += 1
if not opts["multi"]:
break
if matched == 0 and opts["upsert"]:
new_doc = dict(flt)
new_doc.update(upd.get("$set", {}))
docs.append(new_doc)
stats["inserted"] += 1
elif kind == "delete":
_, flt, opts = op
limit = opts["limit"]
kept = []
removed = 0
for d in docs:
hit = all(d.get(k) == v for k, v in flt.items())
if hit and (limit == 0 or removed < limit):
removed += 1
else:
kept.append(d)
self.namespaces[namespace] = docs = kept
stats["deleted"] += removed
return stats
def execute_query(self, namespace, flt, projection=None, sort=None):
docs = self.namespaces.get(namespace, [])
matched = []
for d in docs:
ok = True
for k, cond in flt.items():
if isinstance(cond, dict) and "$gt" in cond:
if not (d.get(k) is not None and d.get(k) > cond["$gt"]):
ok = False
elif d.get(k) != cond:
ok = False
if ok:
matched.append(dict(d))
if sort:
for k, direction in reversed(list(sort.items())):
matched.sort(key=lambda x, f=k: x.get(f), reverse=(direction == -1))
if projection and projection.get("_id") == 0:
for d in matched:
d.pop("_id", None)
return matched
def main():
mgr = MockPhpManager("mongodb://localhost:27017")
# Case 1: BulkWrite insert + WriteConcern MAJORITY
b1 = MockBulkWrite()
oid = b1.insert({"name": "DevDocs Portal"})
res1 = mgr.execute_bulk_write("test.demo_sites", b1, write_concern="majority:1000ms")
c1_actual = {"uri": mgr.uri, "generated_oid_len": len(oid), "inserted": res1["inserted"], "wc": res1["write_concern"]}
c1_expected = {"uri": "mongodb://localhost:27017", "generated_oid_len": 24, "inserted": 1, "wc": "majority:1000ms"}
# Case 2: Insert 3 sites and executeQuery with $gt: 1, projection {_id: 0}, sort {x: -1}
b2 = MockBulkWrite()
b2.insert({"x": 1, "name": "DevDocs", "url": "https://docs.example.org"})
b2.insert({"x": 2, "name": "Google", "url": "https://www.google.com"})
b2.insert({"x": 3, "name": "Taobao", "url": "https://www.taobao.com"})
mgr.execute_bulk_write("test.sites", b2)
q_res = mgr.execute_query("test.sites", {"x": {"$gt": 1}}, projection={"_id": 0}, sort={"x": -1})
c2_actual = q_res
c2_expected = [
{"x": 3, "name": "Taobao", "url": "https://www.taobao.com"},
{"x": 2, "name": "Google", "url": "https://www.google.com"},
]
# Case 3: BulkWrite update ($set multi=false) & delete (limit=1 vs limit=0)
b3 = MockBulkWrite()
b3.update({"x": 2}, {"$set": {"name": "DevTools", "url": "https://tools.example.org"}}, multi=False, upsert=False)
b3.insert({"x": 2, "name": "Duplicate x=2", "url": "https://dup.example.org"})
mgr.execute_bulk_write("test.sites", b3)
updated_names = [d["name"] for d in mgr.execute_query("test.sites", {"x": 2}, projection={"_id": 0})]
b4 = MockBulkWrite()
b4.delete({"x": 1}, limit=1) # delete single matching doc
b4.delete({"x": 2}, limit=0) # delete all matching docs
del_stats = mgr.execute_bulk_write("test.sites", b4)
remaining_x = [d["x"] for d in mgr.execute_query("test.sites", {}, projection={"_id": 0})]
c3_actual = {
"x2_names_before_delete": updated_names,
"deleted_total": del_stats["deleted"],
"remaining_x": remaining_x,
}
c3_expected = {
"x2_names_before_delete": ["DevTools", "Duplicate x=2"],
"deleted_total": 3,
"remaining_x": [3],
}
cases = [
{
"name": "php7_manager_and_bulkwrite_insert",
"summary": "Verify PHP 7/8 MongoDB\\Driver\\Manager, BulkWrite::insert, ObjectId, and WriteConcern::MAJORITY.",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "php7_query_filter_projection_sort",
"summary": "Verify MongoDB\\Driver\\Query with $gt filter, _id exclusion projection, and descending sort.",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "php7_bulkwrite_update_and_delete_limits",
"summary": "Verify BulkWrite::update ($set) and BulkWrite::delete distinguishing limit=1 (single) vs limit=0 (all).",
"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-php7-mongdb-tutorial-lab/explore-php7-mongdb-tutorial.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-php7-mongdb-tutorial.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联49章) · 含当前章节或实例 · mbskycom202612a1732.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1762.zip