Mongodb PHP - Integers with decimals

后端 未结 3 2010
时光取名叫无心
时光取名叫无心 2020-12-21 06:39

This is a follow up to another post i made about inserting an integer into mongodb. I have this working just fine by using the (int) but now when it inserts the number into

3条回答
  •  伪装坚强ぢ
    2020-12-21 07:03

    See what $_POST["number"]; is actually giving you by printing it out. I have a feeling that your problem lies in the input. All of these work as expected:

    $collection->insert(array("test"=>"a","float"=>123.45));
    $collection->insert(array("test"=>"b","float"=>floatval("123.45")));
    $test = array("test"=>"c","float"=>123.45);
    $collection->insert($test);
    

    results in:

    db.test.find();
    { "_id" : ObjectId("4f2036a6eabc88dd0e000006"), "test" : "a", "float" : 123.45 }
    { "_id" : ObjectId("4f2036a6eabc88dd0e000007"), "test" : "b", "float" : 123.45 }
    { "_id" : ObjectId("4f2036a6eabc88dd0e000008"), "test" : "c", "float" : 123.45 }
    

    Adding some more examples for integers:

    $collection->insert(array("test"=>"inta","int"=>new MongoInt32("12345")));
    $collection->insert(array("test"=>"intb","int"=>new MongoInt64("123456789")));
    

    results in (at least on my system):

    { "_id" : ObjectId("4f20431feabc88cf3500001b"), "test" : "inta", "int" : 12345 }
    { "_id" : ObjectId("4f20431feabc88cf3500001c"), "test" : "intb", "int" : NumberLong(123456789) }
    

    So, you have to be somewhat careful if you want to store numbers as "real integers" in mongodb.

    Update I was corrected by someone at 10gen in that PHP integers are usually stored as integers in mongo, even if the type in the shell shows Number. There is also a setting for the mongo PHP driver that allows you to specify this behavior "native_long". http://php.net/manual/en/mongo.configuration.php

提交回复
热议问题