如何使用 php 扩展 mongodb?安装扩展配置扩展连接 mongodb选择数据库和集合执行操作

如何使用 PHP 扩展 MongoDB
要使用 PHP 扩展 MongoDB,需要按照以下步骤操作:
1. 安装扩展
2. 配置扩展
立即学习“PHP免费学习笔记(深入)”;
在 php.ini 中添加以下行:
<code>extension=mongodb.so</code>
3. 连接 MongoDB
使用以下代码连接到 MongoDB:
<code class="php"><?php $client = new MongoDB\Client();</code>
4. 选择数据库和集合
使用以下代码选择数据库和集合:
<code class="php"><?php
$db = $client->selectDatabase('my_database');
$collection = $db->selectCollection('my_collection');</code>5. 执行操作
现在可以使用 MongoDB\Collection 类来执行 CRUD 和其他操作:
-
插入文档:
<code class="php">$collection->insertOne(['name' => 'John Doe']);</code>
-
查找文档:
<code class="php">$cursor = $collection->find(['name' => 'John Doe']);</code>
-
更新文档:
<code class="php">$collection->updateOne(['name' => 'John Doe'], ['$set' => ['age' => 30]]);</code>
-
删除文档:
<code class="php">$collection->deleteOne(['name' => 'John Doe']);</code>
示例
以下是一个使用 PHP MongoDB 扩展的基本示例:
<code class="php"><?php
// 引入扩展
require_once 'vendor/autoload.php';
// 连接到 MongoDB
$client = new MongoDB\Client();
// 选择数据库和集合
$db = $client->selectDatabase('test');
$collection = $db->selectCollection('users');
// 插入文档
$collection->insertOne(['name' => 'John Doe', 'age' => 30]);
// 查找文档
$cursor = $collection->find(['name' => 'John Doe']);
// 遍历并打印结果
foreach ($cursor as $document) {
echo $document['name'] . ' is ' . $document['age'] . ' years old.' . PHP_EOL;
}</code>











