MongoDB PHP7
系统讲解适用于 PHP 7/8 环境的现代 `mongodb` 扩展安装步骤与底层类库(Manager、BulkWrite、Query、WriteConcern、ObjectId)的增删改查实操,并在离线脚本中验证过滤排序与删除 limit 差异。
学完这一章,你能够
- 系统讲解适用于 PHP 7/8 环境的现代 `mongodb` 扩展安装步骤与底层类库(Manager、BulkWrite、Query、WriteConcern、ObjectId)的增删改查实操,并在离线脚本中验证过滤排序与删除 limit 差异。
PHP 7/8 mongodb 扩展安装与连接入口
现代 PHP 7 及 PHP 8 环境统一使用全新的 `mongodb` 扩展(不再兼容 PHP 5 时代的 `mongo` 扩展)。安装时执行对应 PHP 目录下的 `pecl install mongodb`,编译完成后提示将 `extension=mongodb.so` 写入 `php.ini`;既可手动编辑,也可利用 `php --ini` 定位已加载的配置文件路径直接追加该行(若 PHP 不在 `/usr/local/php7/`,需按实际安装路径调整命令前缀)。
新版底层驱动的核心连接入口为 `$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");`,它负责维护与 MongoDB 服务端或副本集的长连接池,并通过命名空间字符串(格式 `数据库名.集合名`)调度各类读写命令。
BulkWrite 写入更新删除与 Query 条件检索
插入文档需实例化 `MongoDB\Driver\BulkWrite`,调用 `$bulk->insert(['_id' => new MongoDB\BSON\ObjectId, 'name' => 'DevDocs Portal'])` 暂存写操作,再搭配 `WriteConcern(WriteConcern::MAJORITY, 1000)` 通过 `$manager->executeBulkWrite('test.demo_sites', $bulk, $writeConcern)` 提交。查询文档则构造 `MongoDB\Driver\Query($filter, $options)`——例如筛选 `['x' => ['$gt' => 1]]`、设置 `projection => ['_id' => 0]` 与 `sort => ['x' => -1]`——调用 `$manager->executeQuery('test.sites', $query)` 后遍历返回的 `stdClass` 文档对象(实测按 `x` 降序输出 `x=3` 与 `x=2` 两条站点记录)。
更新与删除同样经由 `BulkWrite` 批量提交:`$bulk->update(['x' => 2], ['$set' => ['name' => 'DevTools', 'url' => 'https://tools.example.org']], ['multi' => false, 'upsert' => false])` 精确更新单条匹配文档而不触发插入;删除时需格外留意 `limit` 选项语义——`['limit' => 1]` 表示只删除匹配到的第一条文档,而 `['limit' => 0]` 表示删除所有匹配文档。离线脚本完整验证了 BulkWrite 插入、Query 过滤排序投影以及 `limit=1` 与 `limit=0` 删除差异。
离线验证 PHP 7/8 Manager/BulkWrite/Query 与 delete limit=1 vs limit=0 契约
"""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()
- 在离线脚本中确认 ObjectId 生成与 MAJORITY 写关注、$gt 过滤 + _id 排除 + 降序排序查询、$set 更新以及 limit=1/0 删除条数全部一致。
所需环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。
当前源码 SHA256:38721f192fb3dc5bfb9ace345f2def1e324f107ceb9628340ab99c6dad2c8400
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。
ZIP SHA256:d5eba9418c60bcf29dd8e6fe220d85fb2898b18ed6d8d36140b272e9c4cac3de
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 PHP MongoDB\Driver\BulkWrite::delete() 中,参数 ['limit' => 0] 和 ['limit' => 1] 分别代表什么含义?
展开参考解答
['limit' => 1] 表示仅删除第一条满足过滤条件的文档;['limit' => 0] 表示不设上限,删除所有满足条件的匹配文档。