资料:
- 文档: https://packagist.org/packages/mongodb/mongodb
- 驱动安装:https://docs.mongodb.com/drivers/php/
- CURD: https://docs.mongodb.com/php-library/current/tutorial/crud/
安装
# 依赖扩展库 mongodb
$ pecl install mongodb
$ echo "extension=mongodb.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`
$ composer require mongodb/mongodb
使用示例
<?php
require __DIR__ . '/vendor/autoload.php';
// 连接字符串
// mongodb://<username>:<password>@<address>:<port>
$client = new MongoDB\Client('mongodb://127.0.0.1:27017');
// $client->selectDatabase('data');
$db = $client->data;
// $db->selectCollection('users');
$table = $db->users;
// insert
$result = $table->insertOne([
'name' => 'Tom',
'age' => 23,
]);
$result->getInsertedId();
// findOne
// 直接查询字符串形式的 _id不能获取到数据,需要传入一个ObjectId对象
$id = new MongoDB\BSON\ObjectId('6127613a52c83dfeff124962');
$result = $table->findOne([
'_id' => $id
]);
var_dump($result);
echo $result['name'] . PHP_EOL; // Tom
echo $result['age'] . PHP_EOL; // 23
echo $result['_id'] . PHP_EOL; // 6127613a52c83dfeff124962
// 查询数量
$total = $table->countDocuments($where);
// 查询列表 条件 分页 排序 转数组
$list = $table->find($where, [
'limit' => $size,
'skip' => ($page - 1) * $size,
'sort' => [
// desc
'update_time' => -1
],
])->toArray();
// updateOne
$result = $table->updateOne(
['_id' => $id],
['$set' => ['age' => 24]]
);
// deleteOne
$table->deleteOne(['_id' => $id]);