1. 安装 MongoDB PHP Library:
你可以使用 Composer 安装 MongoDB PHP Library:
composer require mongodb/mongodb
2. 连接到 MongoDB 数据库:
<?php
require 'vendor/autoload.php';
use MongoDB\Client;
try {
$client = new Client("mongodb://localhost:27017");
echo "Connected to MongoDB successfully";
} catch (MongoDB\Driver\Exception\ConnectionException $e) {
echo "Failed to connect to MongoDB: " . $e->getMessage();
}
?>
3. 选择数据库和集合:
<?php
require 'vendor/autoload.php';
use MongoDB\Client;
$client = new Client("mongodb://localhost:27017");
$database = $client->selectDatabase('mydb');
$collection = $database->selectCollection('mycollection');
?>
4. 插入文档:
<?php
require 'vendor/autoload.php';
use MongoDB\Client;
$client = new Client("mongodb://localhost:27017");
$database = $client->selectDatabase('mydb');
$collection = $database->selectCollection('mycollection');
$document = [
'name' => 'John Doe',
'age' => 30,
'city' => 'New York'
];
$result = $collection->insertOne($document);
echo "Document inserted successfully with ID: " . $result->getInsertedId();
?>
5. 查询文档:
<?php
require 'vendor/autoload.php';
use MongoDB\Client;
$client = new Client("mongodb://localhost:27017");
$database = $client->selectDatabase('mydb');
$collection = $database->selectCollection('mycollection');
$cursor = $collection->find();
foreach ($cursor as $document) {
var_dump($document);
}
?>
6. 更新文档:
<?php
require 'vendor/autoload.php';
use MongoDB\Client;
$client = new Client("mongodb://localhost:27017");
$database = $client->selectDatabase('mydb');
$collection = $database->selectCollection('mycollection');
$filter = ['name' => 'John Doe'];
$update = ['$set' => ['age' => 31]];
$result = $collection->updateOne($filter, $update);
echo "Document updated successfully";
?>
这些示例展示了使用 MongoDB PHP Library 连接到 MongoDB 数据库、插入文档、查询文档和更新文档的基本操作。你可以根据实际需求使用 MongoDB PHP Library 进行更复杂的操作,例如删除、索引、聚合等。详细的 API 文档和示例可以在 MongoDB 官方网站上找到。
转载请注明出处:http://www.zyzy.cn/article/detail/9253/MongoDB