一个版本为3.2的thinkphp项目打算使用mongodb进行接口的读写工作,由于thinkphp自带的mongodb driver版本太老,需自己开发个简单的driver来管理各种方法。现把在开发中个人感觉比较重要的信息点记录下来。
1、新版mongodb的连接方式,使用 \MongoDB\Driver\Manager类:
1 $this->_conn = new \MongoDB\Driver\Manager($conf["url"] . "/{$conf["dbname"]}");
2、mongodb以文档的形式储存数据,也就是以多维数组形式储存;新版的mongodb增删改主要使用\MongoDB\Driver\BulkWrite类:
1 $bulk = new \MongoDB\Driver\BulkWrite;
新增操作(返回记录id,与mysql的id是不一样的):
1 $id = $bulk->insert($documents);
修改操作,第一个参数为修改条件,第二个是修改的数值,第三个是额外选项(可选),例如如果$option = ['multi' => true]就会修改所有符合条件的数据,默认为只修改匹配的第一条;
1 $bulk->update($this->_where, $updates, $option);
删除操作,第一个参数为删除条件,第二个是额外选项,例如如果设置['limit' => 1]则只删除1条记录:
1 $bulk->delete($this->_where, $option);
添加了上述操作后,执行操作:
1 $writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000); 2 $result = $this->_conn->executeBulkWrite($this->_db . '.' . $this->_prefix . $this->_table, $bulk, $writeConcern); 3 4 /* If the WriteConcern could not be fulfilled */ 5 if ($writeConcernError = $result->getWriteConcernError()) { 6 throw new \Exception("%s (%d): %s\n", $writeConcernError->getMessage(), $writeConcernError->getCode(), var_export($writeConcernError->getInfo(), true)); 7 } 8 9 return true;
3、查询。
mongodb可查询到多重嵌套的数据,例如如果数据格式如下:
1 [ 2 'supplier' => 'Skyworth', 3 'data' => [ 4 'id' => 2, 5 'height' => 150, 6 'weight' => [ 7 'morning' => 5, 8 'night' => [4,5,6], 9 ], 10 ] 11 ]
要查询到'morning’字段的信息,可在where条件那里填写['data.weight.morning' => 5]来进行筛选,普通的查询方法使用\MongoDB\Driver\Query类进行查询:
1 $query = new \MongoDB\Driver\Query($this->_where, $writeOps); 2 $readPreference = new \MongoDB\Driver\ReadPreference(\MongoDB\Driver\ReadPreference::RP_PRIMARY); 3 $cursor = $this->_conn->executeQuery($this->_db . "." . $this->_prefix . $this->_table, $query, $readPreference); 4 var_dump($cursor->toArray());
4、聚合(aggregate)操作
聚合操作类似于mysql把数据整合,获得平均值,最大值等操作;主要使用\MongoDB\Driver\Command类:
1 $command = new \MongoDB\Driver\Command($this->_where); 2 $cursor = $this->_conn->executeCommand($this->_db ,$command); 3 var_dump($cursor->toArray());
在查询方法的写法上费了老大的劲,目前只了解一种写法:
1 [ 2 'aggregate' => 'api_record', 3 'pipeline' => [ 4 [ 5 '$match' => ['supplier' => 'JD'], 6 '$group' => ['_id' => '$supplier', 'sum' => ['$sum' => '$data.height']] 7 ], 8 ], 9 'cursor' => new \stdClass, 10 ]
aggregate为要操作的集合(mysql的表),pipeline为需要操作的集合(注意这里的数组里边还得加上一个数组)。要操作的表达式前面有一个$的符号,上面的操作是先$match匹配supplier字段为JD的数据,然后通过$group分组,获得他们数据里边,data字段里边的height字段的数据总和(这里肯定是只获得一条数据。。)。而cursor的意思是把查询出来的数据格式优化成能看懂的格式。
暂时记录到这里,在后面开发再继续补充。