Home > php教程 > php手册 > PHP驱动MongoDB整数问题的BUG和策略

PHP驱动MongoDB整数问题的BUG和策略

WBOY
Release: 2016-06-21 08:54:58
Original
835 people have browsed it

本文所说的整数问题,其实并不是MongoDB的问题,而是PHP驱动的问题:MongoDB本身有两种整数类型,分别是:32位整数和64位整数,但旧版的PHP驱动不管操作系统是32位还是64位,把所有整数都当做32位整数处理,结果导致64位整数被截断。为了在尽可能保持兼容性的前提下解决这个问题,新版PHP驱动加入了mongo.native-long选项,以期在64位操作系统中把整数都当做64位来处理,有兴趣的可参考:64-bit integers in MongoDB

那么PHP驱动真的完全解决了整数问题么?NO!在处理group操作的时候还有BUG

为了说明问题,我们先来生成一些测试数据:

<font face="NSimsun"><?php <br/><br>ini_set("mongo.native_long", 1);<br><br>$instance = new Mongo();<br><br>$instance = $instance->selectCollection("test", "test");<br><br>for ($i = 0; $i     $instance->insert(array(<br>        "group_id" => rand(1, 5),<br>        "count"    => rand(1, 5),<br>    ));<br>}<br><br>?></font>

下面让我们使用group操作,根据group_id分组,汇总计算count:

<font size="2" face="新宋体"><?php <br/><br>ini_set("mongo.native_long", 1);<br><br>$instance = new Mongo();<br><br>$instance = $instance->selectCollection("test", "test");<br><br>$keys = array("group_id" => 1);<br><br>$initial = array("count" => 0);<br><br>$reduce = "<br>    function(obj, prev) {<br>        prev.count += obj.count;<br>    }<br>";<br><br>$result = $instance->group($keys, $initial, $reduce);<br><br>var_dump($result);<br><br>?></font>

结果和预想的有出入,count没有实现累加,而是变成了[object Object],目前,如果必须使用group操作,那么有两种方法可以缓解这个问题:

<font size="2" face="新宋体">ini_set("mongo.native_long", 0);</font>

<font size="2" face="新宋体">$initial = array("count" => (float)0);</font>

这两种方法都是治标不治本的权宜之计,既然当前PHP驱动里group的实现有问题,那我们就绕开它,用其它的方式实现同样的功能,这个方式就是MapReduce

<font size="2" face="新宋体"><?php <br/><br>ini_set("mongo.native_long", 1);<br><br>$instance = new Mongo();<br><br>$instance = $instance->selectDB("test");<br><br>$map = "<br>    function() {<br>        emit(this.group_id, this.count);<br>    }<br>";<br><br>$reduce = "<br>    function(key, values) {<br>        var sum = 0;<br><br>        for (var index in values) {<br>            sum += values[index];<br>        }<br><br>        return sum;<br>    }<br>";<br><br>$result = $instance->command(array(<br>    "mapreduce" => "test",<br>    "map"       => $map,<br>    "reduce"    => $reduce<br>));<br><br>$result = iterator_to_array($instance->{$result["result"]}->find());<br><br>var_dump($result);<br><br>?></font>

把大象放冰箱里需要三步,而使用MapReduce仅仅需要Map和Reduce两步即可,这里有一个PDF文档生动的说明了MySQL中GROUP BY和MongoDB中MapReduce的对应关系:

 

SQL to MongoDB

此外,还有很多资料可供参考,如:MongoDB Aggregation III: Map-Reduce Basics

说明:软件版本为MongoDB(1.6.5),PECL Mongo(1.1.4)。不同版本结论可能不同。



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template