thinkphp3.2使用新版本mongodb

一个版本为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());

\MongoDB\Driver\Query有两个参数,除了第一个的where之外,另外的$writeOps可限定字段,例如在php下可这样写:

 

$writeOps = [
 'projection' => [
    '字段1' => 1,
    '字段2' => 1,
    '_id' => 0,
  ]   
]

 

当填写了‘projection’后,mongodb就只会输出你想输出的字段,其中1代表要输出,但'_id'默认是会输出的,如果不想让'_id'输出,只需要填写'_id'为0即可;

 

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的意思是把查询出来的数据格式优化成能看懂的格式。

 

暂时记录到这里,在后面开发再继续补充。

补:aggregate无所不能!!!

 5、Map Reduce

教程中描述在用MongoDB查询返回的数据量很大的情况下,做一些比较复杂的统计和聚合操作做花费的时间很长的时候,可以用MongoDB中的MapReduce进行实现,但个人感觉reduce能写的方法没有aggregate提供的表达式多,而且在功能上有点重叠,可能需要进一步的研究。现提供php下的实现方法:

 

$map = <<<JS
        function test(){
            emit({
            'saleUnit':this.saleUnit,
            'upc':this.upc
            }, 2);
        }
JS;

        $map = new \MongoDB\BSON\Javascript($map);
        $reduce = <<<JS
        function test(key, values){
            var total = 0;
            for(var i in values){
                total = parseInt(total) + parseInt(i);
            }
            return total;
        }
JS;
        $reduce = new \MongoDB\BSON\Javascript($reduce);
        $out = 'output_collection_name';
        $data = Mon('member_store_record')->where([
            'mapReduce' => 'suning_product',
            'map' => $map,
            'reduce' => $reduce,
            'out' => 'output_collection_name',
        ])->command(false);
        var_dump($data);

 

mapReduce指使用哪个集合来处理,out指输出结果放到哪个集合,map和reduce方法都是使用js来写的,然后放到\MongoDB\BSON\Javascript类处理。返回结果示例如下:

array (size=4)
      'result' => string 'output_collection_name' (length=22)
      'timeMillis' => int 106
      'counts' => 
        array (size=4)
          'input' => int 4
          'emit' => int 4
          'reduce' => int 1
          'output' => int 2
      'ok' => float 1

注意上面的是map_reduce的处理情况分析,处理的结果应该是在output_collection_name的集合查看。上面结果timeMillis指运行了多少毫秒,input指输入多少条数据,然后最终output输出了多少条数据到output_collection_name集合;

 

 

 

 
 
 
 
posted @ 2018-04-25 18:11  魁奇路潘凤  阅读(1001)  评论(0编辑  收藏  举报