当前位置:首页>php>PHP 操作 MongoDB

PHP 操作 MongoDB

  • 2026-09-02 20:20:25
PHP 操作 MongoDB

PHP 项目中使用 MongoDB。


安装扩展

# 安装 PHP 扩展
pecl install mongodb

# php.ini
extension=mongodb.so

# 安装 Composer 包
composer require mongodb/mongodb

基本使用

<?php
useMongoDB\Client;

$client = new Client('mongodb://root:password@localhost:27017');
$db = $client->mydb;
$collection = $db->users;

// 插入
$result = $collection->insertOne([
'name' => '张三',
'age' => 25,
'email' => 'zhangsan@example.com'
]);
$id = $result->getInsertedId();

// 查询
$user = $collection->findOne(['name' => '张三']);
$users = $collection->find(['age' => ['$gt' => 20]]);

foreach ($users as $user) {
echo $user['name'];
}

// 更新
$collection->updateOne(
    ['name' => '张三'],
    ['$set' => ['age' => 26]]
);

// 删除
$collection->deleteOne(['name' => '张三']);

封装服务类

<?php
namespaceApp\Services;

useMongoDB\Client;
useMongoDB\Collection;

classMongoService
{
private Client $client;
private string $database;

publicfunction__construct()
{
$this->client = new Client(config('mongo.uri'));
$this->database = config('mongo.database');
    }

publicfunctioncollection(string $name): Collection
{
return$this->client->{$this->database}->{$name};
    }

publicfunctionfind(string $collection, array $filter = [], array $options = []): array
{
        $cursor = $this->collection($collection)->find($filter, $options);
return iterator_to_array($cursor);
    }

publicfunctionfindOne(string $collection, array $filter): ?array
{
        $doc = $this->collection($collection)->findOne($filter);
return $doc ? (array)$doc : null;
    }

publicfunctioninsert(string $collection, array $data): string
{
        $data['created_at'] = new \MongoDB\BSON\UTCDateTime();
        $result = $this->collection($collection)->insertOne($data);
return (string)$result->getInsertedId();
    }

publicfunctionupdate(string $collection, array $filter, array $data): int
{
        $data['updated_at'] = new \MongoDB\BSON\UTCDateTime();
        $result = $this->collection($collection)->updateMany($filter, ['$set' => $data]);
return $result->getModifiedCount();
    }

publicfunctiondelete(string $collection, array $filter): int
{
        $result = $this->collection($collection)->deleteMany($filter);
return $result->getDeletedCount();
    }

publicfunctionaggregate(string $collection, array $pipeline): array
{
        $cursor = $this->collection($collection)->aggregate($pipeline);
return iterator_to_array($cursor);
    }
}

日志存储示例

<?php
classLogService
{
private MongoService $mongo;

publicfunctionlog(string $level, string $message, array $context = []): void
{
$this->mongo->insert('logs', [
'level' => $level,
'message' => $message,
'context' => $context,
'ip' => request()->ip(),
'user_id' => auth()->id(),
'url' => request()->fullUrl()
        ]);
    }

publicfunctionquery(array $filter, int $page = 1, int $size = 50): array
{
return$this->mongo->find('logs', $filter, [
'sort' => ['created_at' => -1],
'skip' => ($page - 1) * $size,
'limit' => $size
        ]);
    }

publicfunctionstats(string $startDate, string $endDate): array
{
return$this->mongo->aggregate('logs', [
            ['$match' => [
'created_at' => [
'$gte' => new \MongoDB\BSON\UTCDateTime(strtotime($startDate) * 1000),
'$lte' => new \MongoDB\BSON\UTCDateTime(strtotime($endDate) * 1000)
                ]
            ]],
            ['$group' => [
'_id' => '$level',
'count' => ['$sum' => 1]
            ]]
        ]);
    }
}

总结

操作
PHP 方法
插入
insertOne/insertMany
查询
find/findOne
更新
updateOne/updateMany
删除
deleteOne/deleteMany
聚合
aggregate

MongoDB 适合日志、内容等灵活数据的存储。

最新文章

随机文章