Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumberLong in Mongodb 2.6 when inserting through phpDriver

Tags:

php

mongodb

When you do something like this in Mongo 2.6 db.test.insert({a : 1, b : [2, 3]}) you will get { "_id" : ObjectId("..."), "a" : 3, "b" : [2, 3]}. Nothing unexpected.

When I was doing similar through php in Mongo 2.4.10 with 1.4.5 driver:

$test->insert([
 'a' => 1,
 'b' => [2 ,3]
])

I was still getting the same normal numbers. But when I do something like this in Mongo 2.6.0 the result is different:

{
    "_id" : ObjectId("534a...567"),
    "a" : NumberLong(1),
    "b" : [
        NumberLong(2),
        NumberLong(3)
    ]
}

As you see the numbers are converted to NumberLong. Also that's the same integer (only it can be much bigger), I do not want this behavior, because a) it is longer to read in the shell, b) all my numbers are below 100000 and therefore there is no point to have numberLong there.

I am using php 5.5.10 with mongoDriver 1.5.1

like image 846
Salvador Dali Avatar asked Apr 13 '14 09:04

Salvador Dali


1 Answers

Here is my investigation about it:

MongoShell uses 32-bit numbers by default, and therefore I see these normal numbers in the console. Previously by default all values inserted with phpDriver were 32-bit

I assume this was changed in the driver and by default right now it assumes that values are 64bits. It is possible to come back to normal behavior by doing this manually with MongoInt32()

$test->insert([
    'a' => new MongoInt32(1),
    'b' => [new MongoInt32(2), new MongoInt32(3)]
]);

This will save everything as correct short numbers in the shell. Still looking for a better solution.

Actually looking more closely into my phpinfo() I found that it has the following line mongo.native_long and the value is 1. Actually this is forcing driver to save everything as MongoInt64. And looking at documentation in mongo configuration:

The default behavior for this has been changed to TRUE in 1.5.0, so make sure to set this variable to the value you want (probably TRUE) so that the driver's behavior doesn't suddenly change when you upgrade.

So actually this was changed in 1.5.0 and to set it back I need only to change it to FALSE.

To do this go to your php.ini or mongo.ini and add/change the line mongo.native_long = 0

like image 72
Salvador Dali Avatar answered Sep 28 '22 07:09

Salvador Dali