thinkphp3.2使用新版本mongodb

一个版本为3.2的thinkphp项目打算使用mongodb进行接口的读写工做,因为thinkphp自带的mongodb driver版本太老,需本身开发个简单的driver来管理各类方法。现把在开发中我的感受比较重要的信息点记录下来。php

一、新版mongodb的链接方式,使用 \MongoDB\Driver\Manager类:mysql

1 $this->_conn = new \MongoDB\Driver\Manager($conf["url"] . "/{$conf["dbname"]}");

 

二、mongodb以文档的形式储存数据,也就是以多维数组形式储存;新版的mongodb增删改主要使用\MongoDB\Driver\BulkWrite类:sql

1 $bulk = new \MongoDB\Driver\BulkWrite;

新增操做(返回记录id,与mysql的id是不同的):mongodb

1 $id = $bulk->insert($documents);

修改操做,第一个参数为修改条件,第二个是修改的数值,第三个是额外选项(可选),例如若是$option = ['multi' => true]就会修改全部符合条件的数据,默认为只修改匹配的第一条;thinkphp

1 $bulk->update($this->_where, $updates, $option);

删除操做,第一个参数为删除条件,第二个是额外选项,例如若是设置['limit' => 1]则只删除1条记录:api

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;

三、查询。优化

mongodb可查询到多重嵌套的数据,例如若是数据格式以下:this

 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类进行查询:url

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便可;

 

四、聚合(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无所不能!!!

 五、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集合;

相关文章
相关标签/搜索