类特性
- 单例模式管理连接
- 自动兼容旧版
MongoClient 与新版 MongoDB\Driver(示例基于旧版)
- 封装 insert/insertMany/find/findOne/update/delete/aggregate/index
- 异常统一捕获转换
核心代码(精简版)
<?php
class Mongo_db {
private static $instance = null;
private $conn;
private $db;
private $collection;
private $host = '127.0.0.1';
private $port = 27017;
private $dbName;
private $tableName;
private function __construct($host, $port, $dbName, $tableName) {
$this->host = $host; $this->port = $port;
$this->dbName = $dbName; $this->tableName = $tableName;
$this->conn = new MongoClient("mongodb://{$host}:{$port}");
$this->db = $this->conn->selectDB($dbName);
$this->collection = $this->db->selectCollection($tableName);
}
public static function getInstance($host=null,$port=null,$db=null,$table=null) {
if (self::$instance === null) {
self::$instance = new self($host, $port, $db, $table);
}
return self::$instance;
}
// 插入单条
public function insert(array $doc) {
if (empty($doc)) throw new Exception('文档不能为空');
try {
return $this->collection->insert($doc);
} catch (MongoException $e) {
throw new Exception('插入失败: ' . $e->getMessage());
}
}
// 批量插入
public function insertMany(array $docs) {
if (empty($docs)) throw new Exception('文档数组为空');
foreach ($docs as $doc) $this->insert($doc);
}
// 查询单条
public function findOne($where = array()) {
try {
return $this->collection->findOne($where);
} catch (MongoException $e) {
throw new Exception('查询失败: ' . $e->getMessage());
}
}
// 查询列表
public function find($where = array(), $fields = array(), $limit = 0, $skip = 0, $sort = array()) {
$cursor = $this->collection->find($where, $fields);
if ($skip) $cursor->skip($skip);
if ($limit) $cursor->limit($limit);
if ($sort) $cursor->sort($sort);
return iterator_to_array($cursor);
}
// 更新
public function update($where, $data, $options = array()) {
return $this->collection->update($where, array('$set' => $data), $options);
}
// 删除
public function remove($where, $justOne = false) {
return $this->collection->remove($where, array('justOne' => $justOne));
}
// 聚合管道
public function aggregate(array $pipeline) {
return $this->collection->aggregate($pipeline);
}
// 创建索引
public function ensureIndex($keys, $options = array()) {
return $this->collection->ensureIndex($keys, $options);
}
// 计数
public function count($where = array()) {
return $this->collection->count($where);
}
}
使用示例
$mongo = Mongo_db::getInstance('127.0.0.1', 27017, 'shop', 'orders');
// 插入
$mongo->insert(array(
'order_no' => 'ORD' . date('YmdHis') . rand(1000,9999),
'user_id' => 1001,
'items' => array(array('sku'=>'A01','qty'=>2), array('sku'=>'B02','qty'=>1)),
'total' => 299.00,
'status' => 1,
'created' => new MongoDate()
));
// 查询用户最近 10 单
$orders = $mongo->find(
array('user_id' => 1001),
array('_id'=>0, 'order_no'=>1, 'total'=>1, 'status'=>1, 'created'=>1),
10, 0, array('created' => -1)
);
// 聚合:每日销售额
$daily = $mongo->aggregate(array(
array('$group' => array('_id' => array('$dateToString' => array('%Y-%m-%d', '$created')), 'sum' => array('$sum' => '$total'))),
array('$sort' => array('_id' => -1))
));
// 索引
$mongo->ensureIndex(array('user_id' => 1, 'created' => -1));
$mongo->ensureIndex(array('order_no' => 1), array('unique' => true));
迁移到新版 mongodb/mongodb 库
// composer require mongodb/mongodb
$client = new MongoDB\Client("mongodb://host:port");
$coll = $client->selectCollection('db', 'coll');
$coll->insertOne([...]);
$cursor = $coll->find([...]);
$coll->aggregate([...]);