MongoDB PHP
保留梳理 PHP 5 时期 legacy `mongo` 扩展(MongoClient)的连接、建集合与 CRUD 用法,并明确标注该扩展已在 PHP 7+ 移除及向现代 `mongodb` 扩展与官方 Composer 库迁移的对照关系。
学完这一章,你能够
- 保留梳理 PHP 5 时期 legacy `mongo` 扩展(MongoClient)的连接、建集合与 CRUD 用法,并明确标注该扩展已在 PHP 7+ 移除及向现代 `mongodb` 扩展与官方 Composer 库迁移的对照关系。
Legacy PHP 5 mongo 扩展历史定位与连接建集合
在 PHP 中操作 MongoDB 必须加载对应的 C 驱动扩展。本节保留梳理历史 PHP 5 时代 `mongo` 扩展的经典写法以供维护遗留代码参考;但需特别强调,旧版 `mongo` 扩展已正式停止维护并在 PHP 7 及以上版本被完全移除,所有 PHP 7/8 新项目应直接转向下一节介绍的 `mongodb` 扩展(`MongoDB\Driver\Manager`)与官方高层库 `mongodb/mongodb`。
在 legacy `mongo` 扩展中,调用 `new MongoClient()` 默认连接 `mongodb://localhost:27017`,通过属性访问 `$db = $m->test` 选择数据库(不存在时在写入或建集合后自动创建),并通过 `$db->createCollection("demo_articles")` 显式创建集合。
文档插入、查询、更新、删除与现代 API 迁移
写入文档使用 `$collection->insert($document)` 传入 PHP 关联数组(注意早期资料示例里把键值误写成 `"by", "..."` 会变成数字索引项,正确关联写法应为 `"by" => "DevDocs"`);随后可用 `$collection->find()` 返回游标并通过 `foreach` 遍历输出各文档的 `title` 字段,也可在 MongoDB Shell 中使用 `find().pretty()` 复核入库结果。
更新文档调用 `$collection->update($criteria, array('$set' => array('title' => 'MongoDB 教程')))`(默认只更新首条匹配文档,批量更新需传 `array('multiple' => true)`);删除文档调用 `$collection->remove($criteria, array('justOne' => true))` 限定只删除一条匹配记录。该旧扩展还提供 `findOne()`、`save()`、`limit()`、`skip()`、`sort()` 等方法。迁移至现代 PHP 7/8 时,应分别替换为 `insertOne/insertMany`、`updateOne/updateMany` 与 `deleteOne/deleteMany`。离线脚本已完整核验该 CRUD 契约与迁移映射。
离线验证 legacy PHP mongo 扩展 CRUD 契约及向 PHP 7/8 现代驱动 API 迁移映射
"""Offline legacy PHP 5 `mongo` driver CRUD contract & PHP 7/8 migration verifier."""
import json
VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"
class LegacyMongoCollection:
def __init__(self, name):
self.name = name
self.docs = []
def insert(self, doc):
self.docs.append(dict(doc))
return True
def find(self):
return [dict(d) for d in self.docs]
def update(self, criteria, modifier):
updated = 0
for d in self.docs:
if all(d.get(k) == v for k, v in criteria.items()):
if "$set" in modifier:
d.update(modifier["$set"])
updated += 1
break # legacy default updates first matching document unless multiple=true
return updated
def remove(self, criteria, just_one=False):
removed = 0
kept = []
for d in self.docs:
matched = all(d.get(k) == v for k, v in criteria.items())
if matched and (not just_one or removed == 0):
removed += 1
else:
kept.append(d)
self.docs = kept
return removed
def main():
# Case 1: Connection defaults & collection creation
default_uri = "mongodb://localhost:27017"
col = LegacyMongoCollection("demo_articles")
c1_actual = {"default_uri": default_uri, "db": "test", "collection": col.name}
c1_expected = {"default_uri": "mongodb://localhost:27017", "db": "test", "collection": "demo_articles"}
# Case 2: insert() + find() iteration (fixing associative key typo "by" => "DevDocs")
col.insert({
"title": "MongoDB",
"description": "database",
"likes": 100,
"url": "https://example.org/mongodb/",
"by": "DevDocs",
})
col.insert({
"title": "MongoDB 教程",
"description": "second copy",
"likes": 50,
"url": "https://example.org/mongodb-2/",
"by": "DevDocs",
})
titles_before = [d["title"] for d in col.find()]
c2_actual = {"count": len(titles_before), "titles": titles_before}
c2_expected = {"count": 2, "titles": ["MongoDB", "MongoDB 教程"]}
# Case 3: update($set) and remove(justOne=True) behavior + modern migration mapping
mod_count = col.update({"title": "MongoDB"}, {"$set": {"title": "MongoDB 教程"}})
titles_after_update = [d["title"] for d in col.find()]
removed_count = col.remove({"title": "MongoDB 教程"}, just_one=True)
remaining_count = len(col.find())
migration_map = {
"MongoClient": "MongoDB\\Client (mongodb/mongodb) or MongoDB\\Driver\\Manager",
"insert": "insertOne / insertMany / BulkWrite::insert",
"update": "updateOne / updateMany / BulkWrite::update",
"remove": "deleteOne / deleteMany / BulkWrite::delete",
}
c3_actual = {
"modified": mod_count,
"titles_after_update": titles_after_update,
"removed_with_just_one": removed_count,
"remaining_after_just_one": remaining_count,
"migration_targets": sorted(migration_map.keys()),
}
c3_expected = {
"modified": 1,
"titles_after_update": ["MongoDB 教程", "MongoDB 教程"],
"removed_with_just_one": 1,
"remaining_after_just_one": 1,
"migration_targets": ["MongoClient", "insert", "remove", "update"],
}
cases = [
{
"name": "legacy_php_connect_and_create_collection",
"summary": "Verify legacy MongoClient default localhost:27017 connection and collection handle selection.",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "legacy_php_insert_and_find",
"summary": "Verify associative document insert() and cursor title iteration.",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "legacy_php_update_remove_and_migration",
"summary": "Verify $set update, remove(justOne=true) deleting only one match, and PHP 7/8 API migration mapping.",
"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()
- 离线验证脚本确认默认连接地址、关联文档插入遍历、$set 更新、remove(justOne=true) 单条删除行为以及现代驱动替换方法映射全部通过。
所需环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。
当前源码 SHA256:f72a4f6079deb23a7a200c4fcfc3cfa1a0b2ad9a8a69b89e2dd3ca5adc30dfa7
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。
ZIP SHA256:9930bbf7ec8a43bd030af182c4e2c1ea13d0ec25a71808eec52c334987864b3e
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 PHP 8.x 环境中运行旧代码里的 new MongoClient() 会发生什么,应如何迁移?
展开参考解答
会直接抛出 Class 'MongoClient' not found 致命错误,因为旧版 mongo 扩展不支持 PHP 7/8;应安装 pecl mongodb 扩展并引入 Composer 包 mongodb/mongodb,改用 new MongoDB\Client() 及 insertOne/updateOne/deleteOne API。