PyMongo misbehaving with floating point numbers

1.1k views Asked by At

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.

2

There are 2 answers

0
HM Manya On BEST ANSWER

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 } 
3
bakkal On

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