1. 安装 MongoDB PHP 扩展:
你可以通过 PECL 工具安装 MongoDB PHP 扩展:
pecl install mongodb
2. 添加扩展到 PHP.ini:
编辑 PHP 配置文件(php.ini)并添加以下行:
extension=mongodb.so
3. 连接到 MongoDB 数据库:
<?php
try {
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
echo "Connected to MongoDB successfully";
} catch (MongoDB\Driver\Exception\ConnectionException $e) {
echo "Failed to connect to MongoDB: " . $e->getMessage();
}
?>
4. 插入文档:
<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulk = new MongoDB\Driver\BulkWrite;
$document = ['name' => 'John Doe', 'age' => 30, 'city' => 'New York'];
$bulk->insert($document);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('mydb.mycollection', $bulk, $writeConcern);
echo "Document inserted successfully";
?>
5. 查询文档:
<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$query = new MongoDB\Driver\Query([]);
$cursor = $manager->executeQuery('mydb.mycollection', $query);
foreach ($cursor as $document) {
var_dump($document);
}
?>
6. 更新文档:
<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulk = new MongoDB\Driver\BulkWrite;
$filter = ['name' => 'John Doe'];
$update = ['$set' => ['age' => 31]];
$bulk->update($filter, $update);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('mydb.mycollection', $bulk, $writeConcern);
echo "Document updated successfully";
?>
这些示例展示了连接到 MongoDB 数据库、插入文档、查询文档和更新文档的基本操作。你可以根据实际需求使用 MongoDB PHP 扩展进行更复杂的操作,例如删除、索引、聚合等。详细的 API 文档和示例可以在 MongoDB 官方网站上找到。
转载请注明出处:http://www.zyzy.cn/article/detail/9252/MongoDB