Appearance
MongoDB PHP7
PHP 7+ 与 mongodb 扩展
当前官方 mongodb 扩展(PECL mongodb)支持 PHP 7.0 及以上,包括 PHP 8。旧版 mongo 扩展已废弃,不要在 PHP7/8 上使用。
安装要点
- PHP 版本:用
php -v确认为 7.x 或 8.x。 - 扩展:
pecl install mongodb或从 PECL 下载对应 PHP 版本的 DLL(Windows)。 - Composer 库:
mongodb/mongodb与 PHP 7/8 兼容。
类型与返回值
PHP 7+ 强调类型,MongoDB 驱动返回的 BSON 会映射为 PHP 类型(如 int、string、array、MongoDB\BSON\ObjectId 等)。插入时可直接使用 PHP 数组,驱动会转为 BSON。
示例(PHP 7+)
php
<?php
declare(strict_types=1);
$client = new MongoDB\Client("mongodb://localhost:27017");
$coll = $client->selectDatabase("mydb")->selectCollection("users");
$coll->insertOne(["name" => "test", "age" => 25]);
$doc = $coll->findOne(["name" => "test"]);若使用 PHP 8,可充分利用属性类型与命名参数。驱动与库的更新说明见 MongoDB PHP 文档。下一节介绍 Node.js MongoDB。