分享下mongodb封装的几个方法

这个是我写的php5.6的 ,但是php7以上就不是这样的实现了,大家要是有php7mongodb的封装类可以发我连接,我看看

<?php
/**
 * Created by sublime.
 * User: XXXX
 * Date: 2017/12/1
 * Time: 15:44
 */

namespace Lib;

use MongoClient;
//下面是驱动类,现在没有用到,我的版本php5.5,如果是php7就要用到这些类
use MongoDB\BSON\ObjectID;
use MongoDB\Driver\BulkWrite;
use MongoDB\Driver\Command;
use MongoDB\Driver\Cursor;
use MongoDB\Driver\Exception\AuthenticationException;
use MongoDB\Driver\Exception\BulkWriteException;
use MongoDB\Driver\Exception\ConnectionException;
use MongoDB\Driver\Exception\InvalidArgumentException;
use MongoDB\Driver\Exception\RuntimeException;
use MongoDB\Driver\Manager;
use MongoDB\Driver\Query as MongoQuery;
use MongoDB\Driver\ReadPreference;
use MongoDB\Driver\WriteConcern;

/**
 * PHP操作mongodb数据库操作类
 */


class MongoDb {
    protected $database    = '';
    protected $mo;

    /**
     * 构造方法
     */
    public function __construct() {
        $database = DBNAME;
        $mongo = $this->getConnect(DBSERVER, DBUSER, DBPASS, DBPORT);
        $this->database = $mongo->$database;
    }
    /**
     * 数据库单例方法
     * @param $server
     * @param $user
     * @param $password
     * @param $port
     * test 测试
     * @return Mongo
     */
    /*public function getConnect($server, $user, $password, $port)
    {
        // echo "mongodb://{$server}:{$port}";die;
        // $mongo = new MongoClient("mongodb://{$server}:{$port}");
        $mongo = new MongoClient("mongodb://{$server}:{$port}");
        return $mongo;
    }*/
    /**
     * 数据库单例方法
     * @param $server
     * @param $user
     * @param $password
     * @param $port
     * @return Mongo
     */
    public function getConnect($server, $user, $password, $port) {
        if (isset($this->mo)) {
            return $this->mo;
        } else {

            if (!empty($server)) {
                if (!empty($port)) {

                    if (!empty($user) && !empty($password)) {
                        $this->mo = new MongoClient("mongodb://{$user}:{$password}@{$server}:{$port}");
                    } else {
                        $this->mo = new MongoClient("mongodb://{$server}:{$port}");
                    }
                } else {
                    $this->mo = new MongoClient("mongodb://{$server}");
                }
            } else {
                $this->mo = new MongoClient();
            }
            return $this->mo;
        }
    }

    /**
     * 查询表中所有数据
     * @param $table
     * @param array $where
     * @param array $sort
     * @param string $limit
     * @param string $skip
     * @return array|int
     */
    public function getAll($table, $where = array(), $sort = array(), $limit = '', $skip = '') {
        if (!empty($where)) {
            $data = $this->database->$table->find($where);
        } else {
            $data = $this->database->$table->find();
        }
        if (!empty($sort)) {
            $data = $data->sort($sort);
        }

        if (!empty($limit)) {
            $data = $data->limit($limit);
        }

        if (!empty($skip)) {
            $data = $data->skip($skip);
        }

        $newData = array();
        while ($data->hasNext()) {
            $newData[] = $data->getNext();
        }
        if (count($newData) == 0) {
            return 0;
        }
        return $newData;
    }
    /**
     * 查询表中所有数据,将_id 对象变成数组
     * @param $table
     * @param array $where
     * @param array $sort
     * @param string $limit
     * @param string $skip
     * @return array
     */
    public function getAllArray($table, $where = array(), $sort = array(), $limit = '', $skip = '') {
        if (!empty($where)) {
            $data = $this->database->$table->find($where);
        } else {
            $data = $this->database->$table->find();
        }

        if (!empty($sort)) {
            $data = $data->sort($sort);
        }

        if (!empty($limit)) {
            $data = $data->limit($limit);
        }

        if (!empty($skip)) {
            $data = $data->skip($skip);
        }

        $newData = array();
        while ($data->hasNext()) {
            $newData[] = $data->getNext();
        }
        if (count($newData) == 0) {
            return 0;
        }
        foreach ($newData as $key => $val) {
            $id = $val['_id']->{'$id'};
            $newData[$key]['_id'] = $id;
        }
        return $newData;
    }
    /**
     * 查询指定一条数据
     * @param $table
     * @param array $where
     * @return int
     */
    public function getOne($table, $where = array()) {
        if (!empty($where)) {
            $data = $this->database->$table->findOne($where);
        } else {
            $data = $this->database->$table->findOne();
        }
        return $data;
    }

    /**
     * 统计个数
     * @param $table
     * @param array $where
     * @return mixed
     */
    public function getCount($table, $where = array()) {
        if (!empty($where)) {
            $data = $this->database->$table->find($where)->count();
        } else {
            $data = $this->database->$table->find()->count();
        }
        return $data;
    }

    /**
     * 直接执行mongo命令
     * @param $sql
     * @return array
     */
    public function toExcute($sql) {
        $result = $this->database->execute($sql);
        return $result;
    }

    /**
     * 分组统计个数
     * @param $table
     * @param $where
     * @param $field
     */
    public function groupCount($table, $where, $field) {
        $cond = array(
            array(
                '$match' => $where,
            ),
            array(
                '$group' => array(
                    '_id' => '$' . $field,
                    'count' => array('$sum' => 1),
                ),
            ),
            array(
                '$sort' => array("count" => -1),
            ),
        );
        $this->database->$table->aggregate($cond);
    }

    /**
     * 删除数据
     * @param $table
     * @param $where
     * @return array|bool
     */
    public function toDelete($table, $where) {
        $re = $this->database->$table->remove($where);
        return $re;
    }

    /**
     * 插入数据
     * @param $table
     * @param $data
     * @return array|bool
     */
    public function toInsert($table, $data) {
        $re = $this->database->$table->insert($data);
        return $re;
    }

    /**
     * 更新数据
     * @param $table
     * @param $where
     * @param $data
     * @return bool
     */
    public function toUpdate($table, $where, $data) {
        $re = $this->database->$table->update($where, array('$set' => $data));
        return $re;
    }

    /**
     * 获取唯一数据
     * @param $table
     * @param $key
     * @return array
     */
    public function distinctData($table, $key, $query = array()) {
        if (!empty($query)) {
            $where = array('distinct' => $table, 'key' => $key, 'query' => $query);
        } else {
            $where = array('distinct' => $table, 'key' => $key);
        }

        $data = $this->database->command($where);
        return $data['values'];
    }
}
?>
操作monodb的c#封装,调用非常方便,可以继承,功能包括: 1、所有数据库操作 2、前台表格类数据获取 public List GetList(List lstColName, Document query, JqGridParam jqParam, ref int count),封装了通用的获取前台表格数据的方法,将在工程中减少大量数据库访问代码,有了这个后对前台表格类查询我们可以不用在Control里使用linq或者封装在Model里然后对前台定义视图类了,使用如下: try { JqGridParam jqParam = new JqGridParam(); jqParam.page = 1; jqParam.rows = 1000; MemberOper memOper = new MemberOper(); MongoBasicOper monOper = new MongoBasicOper(DTName.GROUP_MEMBER); int count = 0; //过滤条件 Document query = new Document(); if (!string.IsNullOrEmpty(find)) { MongoRegex reg = new MongoRegex(".*" + find + ".*"); query.Add(DColName.Name, reg); } query.Add(DColName.GroupId, g); Document[] docStatus = new Document[] { new Document(DColName.Status, RowStatus.Pass), new Document(DColName.Status, RowStatus.Admin) }; query.Add("$or", docStatus); //查询列 List lstColName = new List(); lstColName.Add(DColName.UserId); lstColName.Add(DColName.UserName); //查询数据 var lstRes = monOper.GetListEx(lstColName, query, jqParam, ref count); //转换返回值 JqGrid jg = new JqGrid(); if (count == 0) { return Json(jg.toNull(jqParam), JsonRequestBehavior.AllowGet); } var jsonData = jg.toJson(jqParam, count, lstRes, lstColName); jsonData.param = g; return Json(jsonData, JsonRequestBehavior.AllowGet); } catch (Exception e) { return Json(e.Message, JsonRequestBehavior.AllowGet); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值