This commit is contained in:
Default
2025-03-21 11:13:48 +08:00
parent b09e4fca11
commit 18145e6766
15 changed files with 429 additions and 1216 deletions

View File

@@ -19,7 +19,7 @@ class MongoBase
private static $instance;
public static function getInstance(string $uri, string $dbName): self
public static function getInstance(): self
{
// return [
@@ -28,7 +28,7 @@ class MongoBase
// ];
if (!self::$instance) {
self::$instance = new self($uri, $dbName);
self::$instance = new self();
}
return self::$instance;
}
@@ -38,11 +38,14 @@ class MongoBase
* @param string $uri MongoDB 连接字符串
* @param string $dbName 数据库名称
*/
public function __construct(string $uri, string $dbName)
public function __construct()
{
try {
$this->client = new Client($uri);
$this->db = $this->client->selectDatabase($dbName);
$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());
}
@@ -89,6 +92,11 @@ class MongoBase
}
}
public function getDb(): \MongoDB\Database
{
return $this->db;
}
/**
* 插入多条数据
* @param string $collection 集合名称