提供简洁、链式调用风格的 MongoDB 操作封装,涵盖连接管理、CRUD、索引、聚合管道等常用功能,降低原生驱动使用门槛。
<?php
class MyMongo {
private static $instance = null;
private $conn;
private $db;
private $config = array(
'host' => '127.0.0.1',
'port' => 27017,
'user' => '',
'pass' => '',
'db' => 'default_db'
);
// 单例模式获取实例
public static function getInstance($config = array()) {
if (self::$instance === null) {
self::$instance = new self($config);
}
return self::$instance;
}
private function __construct($config) {
$this->config = array_merge($this->config, $config);
$dsn = "mongodb://";
if ($this->config['user']) {
$dsn .= "{$this->config['user']}:{$this->config['pass']}@";
}
$dsn .= "{$this->config['host']}:{$this->config['port']}";
$this->conn = new MongoClient($dsn);
$this->db = $this->conn->selectDB($this->config['db']);
}
// 切换集合
public function collection($name) {
$this->collection = $this->db->selectCollection($name);
return $this;
}
// 插入单条
public function insert($data) {
return $this->collection->insert($data);
}
// 批量插入
public function insertMany(array $docs) {
return $this->collection->batchInsert($docs);
}
// 查询单条
public function findOne($condition = array(), $fields = array()) {
return $this->collection->findOne($condition, $fields);
}
// 查询列表(支持链式 where/order/limit/skip)
public function find($condition = array()) {
$this->cursor = $this->collection->find($condition);
return $this;
}
public function where($condition) {
// 实际应在 find 时传入,此处为演示链式风格
return $this;
}
public function orderBy($field, $sort = 1) {
$this->cursor->sort(array($field => $sort));
return $this;
}
public function limit($num) {
$this->cursor->limit($num);
return $this;
}
public function skip($num) {
$this->cursor->skip($num);
return $this;
}
public function get() {
return iterator_to_array($this->cursor);
}
// 更新
public function update($condition, $data, $options = array()) {
return $this->collection->update($condition, $data, $options);
}
// 删除
public function remove($condition, $justOne = false) {
return $this->collection->remove($condition, 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);
}
}
// 初始化
$mongo = MyMongo::getInstance(array('db' => 'shop'));
// 插入订单
$mongo->collection('orders')->insert(array(
'order_no' => '20240101001',
'user_id' => 1001,
'amount' => 299.00,
'items' => array(
array('sku' => 'A01', 'qty' => 1),
array('sku' => 'B02', 'qty' => 2)
),
'created_at' => new MongoDate()
));
// 查询用户最近 10 笔订单
$orders = $mongo->collection('orders')
->find(array('user_id' => 1001))
->orderBy('created_at', -1)
->limit(10)
->get();
// 聚合:按日期统计销售额
$stats = $mongo->collection('orders')->aggregate(array(
array('$group' => array('_id' => '$created_at', 'total' => array('$sum' => '$amount'))),
array('$sort' => array('_id' => -1))
));
MongoClient 已废弃,新项目请使用 mongodb/mongodb 官方库(基于 MongoDB\Driver)。BulkWrite 批量操作,减少网络往返。