integer problem mentioned in this article is actually not a problem with MongoDB, but a problem with the PHP driver: MongoDB itself has two integer types, namely: 32-bit integer and 6"/> integer problem mentioned in this article is actually not a problem with MongoDB, but a problem with the PHP driver: MongoDB itself has two integer types, namely: 32-bit integer and 6">
Home > Article > Backend Development > Integer problems and countermeasures when operating MongoDB with PHP_PHP tutorial
本文所说的PHP-138" target=_blank>整数问题,其实并不是MongoDB的问题,而是PHP驱动的问题:MongoDB本身有两种整数类型,分别是:32位整数和64位整数,但旧版的PHP驱动不管操作系统是32位还是64位,把所有整数都当做32位整数处理,结果导致64位整数被截断。为了在尽可能保持兼容性的前提下解决这个问题,新版PHP驱动加入了mongo.native-long选项,以期在64位操作系统中把整数都当做64位来处理,有兴趣的可参考:html" target=_blank>64-bit integers in MongoDB。
那么PHP驱动真的完全解决了整数问题么?NO!在处理group操作的时候还有BUG:
为了说明问题,我们先来生成一些测试数据:
|
下面让我们使用group操作,根据group_id分组,汇总计算count:
|
结果和预想的有出入,count没有实现累加,而是变成了[object Object],目前,如果必须使用group操作,那么有两种方法可以缓解这个问题:
|
|
Both of these methods are expedient measures that treat the symptoms rather than the root cause. Since there is a problem with the implementation of group in the current PHP driver, we will bypass it and use other methods to achieve the same function. This method is MapReduce:
<font face="新宋体" size="2"><?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>
|
It takes three steps to put an elephant in the refrigerator, but using MapReduce only requires two steps, Map and Reduce. Here is a PDF document that vividly illustrates the corresponding relationship between GROUP BY in MySQL and MapReduce in MongoDB:
SQL to MongoDB
In addition, there are many materials for reference, such as: MongoDB Aggregation III: Map-Reduce Basics
.
Note: The software version is MongoDB (1.6.5), PECL Mongo (1.1.4). The conclusions may be different in different versions.The PHP-138" target=_blank> integer problem mentioned in this article is actually not a MongoDB problem, but PHP driver problem: MongoDB itself has two integer types, namely: 32-bit integer and 6...