mongodb基类封装实例

mongodb的基类

  1 <?php
  2
  3 namespace BI\Service\MongoDB;
  4
  5 use MongoDB\Driver\BulkWrite;
  6 use MongoDB\Driver\Exception\Exception;
  7 use MongoDB\Driver\Manager;
  8 use MongoDB\Driver\Query;
  9 use MongoDB\Driver\WriteConcern;
 10 use MongoDB\Driver\WriteResult;
 11 use MongoException;
 12
 13 class MongoDBManager
 14 {
 15     private $mongoManager;
 16     private $db;
 17
 18     function __construct($mongoDBConfig)
 19     {
 20         $connectString = 'mongodb://';
 21         if($mongoDBConfig['user'] && $mongoDBConfig['pass'])
 22             $connectString .= $mongoDBConfig['user'] . ':' . $mongoDBConfig['pass'] . '@';
 23         $connectString .= $mongoDBConfig['host'] . ':' . $mongoDBConfig['port'] . '/' . $mongoDBConfig['db'];
 24         $this->mongoManager = new Manager($connectString);
 25         $this->db = $mongoDBConfig['db'];
 26     }
 27
 28
 29     /**
 30      * @param string $collection
 31      * @param array $filter
 32      * @param array $options
 33      * @return array
 34      */
 35     public function executeQuery($collection, $filter = array(), $options = array()){
 36         $query = new Query($filter, $options);
 37         return $this->mongoManager->executeQuery($this->db . '.' . $collection, $query)->toArray();
 38     }
 39
 40     /**
 41      * @param string $collection
 42      * @param BulkWrite $bulkWrite
 43      * @return WriteResult
 44      */
 45     public function executeBulkWrite($collection, $bulkWrite){
 46         return $this->mongoManager->executeBulkWrite($this->db . '.' . $collection, $bulkWrite);
 47     }
 48
 49     /**
 50      * @param $doc
 51      * @param string $collection
 52      * @param bool $fetched
 53      * @return WriteResult
 54      */
 55     public function insertData($doc, $collection, $fetched = FALSE) {
 56         // do checking
 57         if (empty($doc) || $collection === NULL) {
 58             return false;
 59         }
 60
 61         // save data information
 62         try {
 63             //$wc = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY);
 64
 65             $bulk = new BulkWrite();
 66             $insertedId = $bulk->insert($doc);
 67             $this->mongoManager->executeBulkWrite($this->db . '.' . $collection, $bulk);
 68
 69             //throw new MongoException('insert data failed');
 70
 71             if ($fetched) { return $insertedId; }
 72         }
 73         catch (Exception $e) {
 74             $this->throwError($e->getMessage());
 75         }
 76     }
 77
 78     /**
 79      * Update records
 80      * @param $collection
 81      * @param $filter
 82      * @param $updated
 83      * @param $options
 84      * @return WriteResult
 85      */
 86     public function updateData($collection, $filter, $updated, $options = array()) {
 87         // do checking
 88         if ($collection === NULL || empty($updated) || empty($filter)) {
 89             $this->throwError('Updated data can not be empty!');
 90         }
 91
 92         // do updating
 93         $timeout = 3000;
 94         $wc = new WriteConcern(WriteConcern::MAJORITY, $timeout);
 95         $bulk = new BulkWrite();
 96         $bulk->update($filter, $updated, $options);
 97         try {
 98             // execute
 99             return $this->mongoManager->executeBulkWrite("{$this->db}.$collection", $bulk, $wc);
100
101             // throw new MongoException('find record failed');
102         }
103         catch (\MongoException $e) {
104             $this->throwError($e->getMessage());
105         }
106     }
107
108     /**
109      * Delete record
110      * @param $collection
111      * @param $filter
112      * @param $options
113      * @return number of rows affected
114      */
115     public function deleteData($collection, $filter, $options=array()) {
116         // do checking
117         if ($collection === NULL) {
118             $this->throwError('Inserted data can not be empty!');
119         }
120
121         if (!is_array($filter)) {
122             $this->throwError('$filter format is invaild.');
123         }
124
125         try {
126             // execute
127             $bulk = new BulkWrite();
128             $bulk->delete($filter, $options);
129             $WriteResult = $this->mongoManager->executeBulkWrite("{$this->db}.$collection", $bulk);
130             return $WriteResult->getDeletedCount();
131
132             // throw new MongoException('delete record failed');
133         }
134         catch (MongoException $e) {
135             $this->throwError($e->getMessage());
136         }
137     }
138
139     /**
140      * throw error message
141      * @param string $errorInfo error message
142      */
143     private function throwError($errorInfo='') {
144         echo "<h3>Error:$errorInfo</h3>";
145     }
146 }
 

增删改查

class AlarmController
{
    CONST TIP = 'tip';//我习惯,mongodb里面的key写成常量
    public function checkTipAlarm()
    {
        $mongo = new MongoDBManager()

        //查询
        $result = $mongo->executeQuery(
            self::TIP,
            array(
                '_id' => new ObjectID( $this->request['rid'] )
            )
        );

        //新增
        $document = array(
            "msg" => $this->request['msg'],
            "owner" => $this->uuid,
            "to" => $this->request['to'],
            'type' => $this->request['type'],
            'flag' => self::FLAG_UNREAD,
            "inserted" => $function->millStampTime(),
            "status" => 1,
        );
        $result = $mongo->insertData($document, self::TIP, true);

        //更新
        $result = $mongo->updateData(
            self::TIP,
            array(
                '_id' => new ObjectID( $this->request['rid'] )
            ),
            array('$set' => array('status' => 0))
        );

        //删除
        $result = $mongo->deleteData(
            self::TIP,
            array(
                '_id' => new ObjectID( $this->request['rid'] )
            )
        );
    }
}
上一篇:VS Code常用快捷键大全


下一篇:python—索引与切片总结