PyMongo misbehaving with floating point numbers

五迷三道 提交于 2019-12-11 03:56:33

问题


I am using PyMongo to save data to a MongoDB. THe following is my code:

from pymongo import MongoClient
import time


class data2db:
    def __init__(self):
        pass

    def enter_data(self, data):
        client = MongoClient('127.0.0.1', 27017)
        db = client.db
        coll = db.Temperature1
        post = {"auth": data,
                "Time": time.asctime(time.localtime(time.time()))}
        post_ = coll.insert(post)


c = data2db()

c.enter_data(24.3)

However, when I retrieve this object I get:

{ "_id" : ObjectId("558019749f43b8c19779c106"), "auth" : -0.000063384, "Time" : "Tue Jun 16 08:41:24 2015" }

When I try the same code with integers it is working fine. I am using MongoDB 2.6.3 on RaspberryPi with the latest version of Raspbian and python 2.7.3. I installed Pymongo from the Raspbian repository, via this command:

sudo apt-get install python-pymongo

Can someone please help me out?

Update: The same code behaves perfectly on an intel computer using Ubuntu 14.04 LTS, mongoDB 3.0.1, python 2.7.3 and pyMongo 2.8 but when it comes to Raspbian the behaviour changes. Even in the mongo shell floating point insertions on Raspbian are misbehaving. It may be because of limited floating point support or a deprecated mongoDB version (The binaries for the latest version are not available for ARM). In anycase I'll try it with rpi2 later today and check it makes a difference or not.


回答1:


Based on this

c.enter_data("24.3")

post = {"auth": data, ... # No conversion done internally

You are actually inserting a string, not a float

You should be able to insert floats with c.enter_data(24.3)

To debug further I suggest:

  • Trying the commands on the mongo command line client, to confirm floating point behavior
  • When you insert in the CLI or your Python code, get a hold of the ID of the inserted object, to make sure you are looking at the right object



回答2:


Apparently the insert is working fine but when queried it returns the object in wrong format. When I insert a float from rpi to a remote database then it works just fine. When the object is queried on the computer it was posted to it is displayed as it should be:

`{ "_id" : ObjectId("557d828b08139add2323aeaf"), "A" : 12.1 }` 

but when queried from rpi it displays as:

{ "_id" : ObjectId("557d828b08139add2323aeaf"), "A" : 0.04667261646131403e-60 } 


来源:https://stackoverflow.com/questions/30908471/pymongo-misbehaving-with-floating-point-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!