php7连接mongodb
首先先要安装mongodb扩展
这里提供一个简易的php mongodb类;
<?php /** * Created by PhpStorm. * User: adophper * Date: 2019/1/17 * Time: 15:20 */ /** * mongodb操作类 * Class mongo */ class mongo { public $debug = true; private static $_instance = []; private $_mongo = null; private $_db = null; private function __construct($config) { //如果不是root用户需要在链接后加db: mongodb://username:password@host:port/db if (isset($config['user'])) { $server = sprintf("mongodb://%s:%s@%s:%s/%s", $config['user'], $config['password'], $config['host'], $config['port'], $config['db']); }else { $server = sprintf("mongodb://%s:%s", $config['host'], $config['port']); } $this->_db = $config['db']; try { $this->_mongo = new MongoDBDriverManager($server, ['authMechanism' => 'SCRAM-SHA-256']); }catch (MongoConnectionException $e) { if (self::$debug) { echo $e->getMessage(); } return false; } } public static function getInstance($config) { if (is_object($config)) $config = (array)$config; $k = md5(implode('', $config)); if (!isset(self::$_instance[$k])) { self::$_instance[$k] = new self($config); } return self::$_instance[$k]; } /** * 插入数据 * @param $data * @return MongoDBDriverWriteResult */ public function insert($collection, $document){ $bulk = new MongoDBDriverBulkWrite(); $bulk->insert($document); return $this->_mongo->executeBulkWrite($this->_db.'.'.$collection, $bulk); } /** * 更新文档 * @param $filter * @param $data * @param array $options * @return MongoDBDriverWriteResult */ public function update($collection, $filter, $newObj, $updateOptions = []){ $bulk = new MongoDBDriverBulkWrite(); $bulk->update($filter, $newObj, $updateOptions); $writeConcern = new MongoDBDriverWriteConcern(MongoDBDriverWriteConcern::MAJORITY, 1000); return $this->_mongo->executeBulkWrite($this->_db.'.'.$collection, $bulk, $writeConcern); } /** * 删除文档 * @param $data * @param array $options * @return MongoDBDriverWriteResult */ public function delete($collection, $filter, $deleteOptions = []){ $bulk = new MongoDBDriverBulkWrite(); $bulk->delete($filter, $deleteOptions); $writeConcern = new MongoDBDriverWriteConcern(MongoDBDriverWriteConcern::MAJORITY, 1000); return $this->_mongo->executeBulkWrite($this->_db.'.'.$collection, $bulk, $writeConcern); } /** * 查询文档 * @param $filter * @param array $options * @return MongoDBDriverCursor * @throws MongoDBDriverExceptionException */ public function query($collection, $filter, $options = []){ $query = new MongoDBDriverQuery($filter, $options); return $this->_mongo->executeQuery($this->_db.'.'.$collection, $query); } }