This commit is contained in:
Default
2025-03-23 19:02:52 +08:00
parent 4c4afd37ed
commit 1f5572a1af
14 changed files with 66 additions and 1021 deletions

View File

@@ -1,191 +0,0 @@
<?php
namespace db\mongo;
use MongoDB\Client;
use MongoDB\Exception\Exception as MongoDBException;
use MongoDB\BSON\UTCDateTime;
class MongoBase
{
private $client;
/**
* Undocumented variable
*
* @var \MongoDB\Database
*/
private $db;
private static $instance;
public static function getInstance(): self
{
// return [
// 'uri' => 'mongodb://username:password@your_ip:27017',
// 'database' => 'your_database',
// ];
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
/**
* 构造函数,初始化 MongoDB 连接
* @param string $uri MongoDB 连接字符串
* @param string $dbName 数据库名称
*/
public function __construct()
{
try {
$arrConfig = config('mongodb');
$strUri = sprintf('mongodb://%s:%s@%s:%s', $arrConfig['username'], $arrConfig['password'], $arrConfig['hostname'], $arrConfig['hostport']);
$this->client = new Client($strUri);
$this->db = $this->client->selectDatabase($arrConfig['database']);
} catch (MongoDBException $e) {
throw new \Exception("MongoDB connection failed: " . $e->getMessage());
}
}
/**
* 获取下一个自增序列值
* @param string $sequenceName 序列名称
* @return int 自增 ID
*/
public function getNextSequence(string $sequenceName): int
{
try {
$counters = $this->db->selectCollection('counters');
$result = $counters->findOneAndUpdate(
['_id' => $sequenceName],
['$inc' => ['sequence_value' => 1]],
[
'upsert' => true,
'returnDocument' => \MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
]
);
return $result->sequence_value ?? 1;
} catch (MongoDBException $e) {
throw new \Exception("Failed to generate sequence: " . $e->getMessage());
}
}
/**
* 插入单条数据
* @param string $collection 集合名称
* @param array $data 数据数组
* @return mixed 插入的 ID
*/
public function insertOne(string $collection, array $data)
{
try {
$coll = $this->db->selectCollection($collection);
$data['created_at'] = new UTCDateTime(); // 自动添加创建时间
$result = $coll->insertOne($data);
return $result->getInsertedId();
} catch (MongoDBException $e) {
throw new \Exception("Insert failed: " . $e->getMessage());
}
}
public function getDb(): \MongoDB\Database
{
return $this->db;
}
/**
* 插入多条数据
* @param string $collection 集合名称
* @param array $data 多条数据数组
* @return array 插入的 ID 列表
*/
public function insertMany(string $collection, array $data)
{
try {
$coll = $this->db->selectCollection($collection);
foreach ($data as &$item) {
$item['created_at'] = new UTCDateTime();
}
$result = $coll->insertMany($data);
return $result->getInsertedIds();
} catch (MongoDBException $e) {
throw new \Exception("Insert many failed: " . $e->getMessage());
}
}
/**
* 查询单条数据
* @param string $collection 集合名称
* @param array $filter 查询条件
* @param array $options 查询选项
* @return ?object 查询结果
*/
public function findOne(string $collection, array $filter = [], array $options = []): ?object
{
try {
$coll = $this->db->selectCollection($collection);
return $coll->findOne($filter, $options);
} catch (MongoDBException $e) {
throw new \Exception("Find one failed: " . $e->getMessage());
}
}
/**
* 查询多条数据
* @param string $collection 集合名称
* @param array $filter 查询条件
* @param array $options 查询选项
* @return array 查询结果
*/
public function findMany(string $collection, array $filter = [], array $options = []): array
{
try {
$coll = $this->db->selectCollection($collection);
$cursor = $coll->find($filter, $options);
return iterator_to_array($cursor);
} catch (MongoDBException $e) {
throw new \Exception("Find many failed: " . $e->getMessage());
}
}
/**
* 更新单条数据
* @param string $collection 集合名称
* @param array $filter 查询条件
* @param array $update 更新内容
* @param array $options 更新选项
* @return int 受影响的文档数
*/
public function updateOne(string $collection, array $filter, array $update, array $options = []): int
{
try {
$coll = $this->db->selectCollection($collection);
$update['$set']['updated_at'] = new UTCDateTime(); // 自动添加更新时间
$result = $coll->updateOne($filter, $update, $options);
return $result->getModifiedCount();
} catch (MongoDBException $e) {
throw new \Exception("Update one failed: " . $e->getMessage());
}
}
/**
* 删除数据
* @param string $collection 集合名称
* @param array $filter 查询条件
* @return int 删除的文档数
*/
public function delete(string $collection, array $filter): int
{
try {
$coll = $this->db->selectCollection($collection);
$result = $coll->deleteMany($filter);
return $result->getDeletedCount();
} catch (MongoDBException $e) {
throw new \Exception("Delete failed: " . $e->getMessage());
}
}
}