安装 MongoDB PHP 扩展:
使用 pecl 安装 MongoDB PHP 扩展,确保你的系统已经安装了 PHP 7.x 版本:
pecl install mongodb
或者,如果你使用 Composer,你可以通过以下方式安装:
composer require mongodb/mongodb
连接到 MongoDB:
<?php
require 'vendor/autoload.php'; // 如果使用 Composer 安装
use MongoDB\Client;
// 创建 MongoDB 客户端
$client = new Client("mongodb://localhost:27017");
// 选择数据库
$database = $client->mydb;
echo "Connected to the database successfully";
?>
插入文档:
<?php
use MongoDB\Client;
$client = new Client("mongodb://localhost:27017");
$database = $client->mydb;
$collection = $database->mycollection;
// 插入文档
$document = [
"name" => "John Doe",
"age" => 30,
"city" => "New York"
];
$collection->insertOne($document);
echo "Document inserted successfully";
?>
查询文档:
<?php
use MongoDB\Client;
$client = new Client("mongodb://localhost:27017");
$database = $client->mydb;
$collection = $database->mycollection;
// 查询文档
$cursor = $collection->find();
foreach ($cursor as $document) {
echo json_encode($document), "\n";
}
?>
确保你的 MongoDB PHP 扩展版本与 PHP 7.x 兼容。
转载请注明出处:http://www.zyzy.cn/article/detail/14237/MongoDB