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

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

Jun 21, 2016 am 08:54 AM
mongo mongodb nbsp

本文所说的整数问题,其实并不是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)。不同版本结论可能不同。



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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What to do if navicat expires What to do if navicat expires Apr 23, 2024 pm 12:12 PM

Solutions to resolve Navicat expiration issues include: renew the license; uninstall and reinstall; disable automatic updates; use Navicat Premium Essentials free version; contact Navicat customer support.

Is it difficult to learn nodejs on the front end? Is it difficult to learn nodejs on the front end? Apr 21, 2024 am 04:57 AM

For front-end developers, the difficulty of learning Node.js depends on their JavaScript foundation, server-side programming experience, command line familiarity, and learning style. The learning curve includes entry-level and advanced-level modules focusing on fundamental concepts, server-side architecture, database integration, and asynchronous programming. Overall, learning Node.js is not difficult for developers who have a solid foundation in JavaScript and are willing to invest the time and effort, but for those who lack relevant experience, there may be certain challenges to overcome.

How to connect navicat to mongodb How to connect navicat to mongodb Apr 24, 2024 am 11:27 AM

To connect to MongoDB using Navicat, you need to: Install Navicat Create a MongoDB connection: a. Enter the connection name, host address and port b. Enter the authentication information (if required) Add an SSL certificate (if required) Verify the connection Save the connection

What are the commonly used modules in nodejs? What are the commonly used modules in nodejs? Apr 21, 2024 am 04:34 AM

The most commonly used modules in Node.js include: File system module for file operations Network module for network communication Stream module for processing data streams Database module for interacting with databases Other utility modules such as encryption, query strings String parsing and HTTP framework

What database is good for nodejs? What database is good for nodejs? Apr 21, 2024 am 05:06 AM

For Node.js applications, choosing a database depends on the application requirements. NoSQL databases MongoDB provide flexibility, Redis provides high concurrency, Cassandra handles time series data, and Elasticsearch is dedicated to search. SQL database MySQL has excellent performance, PostgreSQL is feature-rich, SQLite is lightweight, and Oracle Database is comprehensive. When choosing, consider data types, queries, performance, transactionality, availability, licensing, and cost.

How nodejs implements database How nodejs implements database Apr 21, 2024 am 05:42 AM

Connecting to a database in Node.js requires choosing a database system (relational or non-relational) and then establishing a connection using modules specific to that type. Common modules include mysql (MySQL), pg (PostgreSQL), mongodb (MongoDB), and redis (Redis). After the connection is established, you can use query statements to retrieve data and update statements to modify the data. Finally, the connection must be closed when all operations are completed to release resources. Improve performance and security by following these best practices, such as using connection pooling, parameterized queries, and handling errors gracefully.

How to connect nodejs to database How to connect nodejs to database Apr 21, 2024 am 05:07 AM

Steps to connect to a database in Node.js: Install the MySQL, MongoDB or PostgreSQL package. Create a database connection object. Open a database connection and handle connection errors.

What is the use of net4.0 What is the use of net4.0 May 10, 2024 am 01:09 AM

.NET 4.0 is used to create a variety of applications and it provides application developers with rich features including: object-oriented programming, flexibility, powerful architecture, cloud computing integration, performance optimization, extensive libraries, security, Scalability, data access, and mobile development support.

See all articles