Python Driver pymongo, Integers inside array are converted to float

46 views
Skip to first unread message

Samuel Feng

unread,
Jul 28, 2016, 9:10:23 PM7/28/16
to mongodb-user
Dears,

Record in mongo shell(3.2.6):

> db.users.find({_id:ObjectId('576b8ba158e039761d94dcf6')}).pretty()

{

"_id" : ObjectId("576b8ba158e039761d94dcf6"),

"name" : "test",

"roles" : [1,9],

"point" : 0,

"createTime" : ISODate("2016-06-23T15:08:04.130Z")

} 


However, if retrieving this record using pymongo(3.2.2), the "roles" field above, which is array of int, are changed into array of float:


>>> from pymongo import MongoClient

>>> from bson.objectid import ObjectId
>>> client = MongoClient()
>>> db = client.ga
>>> doc = db.users.find_one({'_id':ObjectId('576b8ba158e039761d94dcf6')})
>>> print doc
{u'_id': ObjectId('576b8ba158e039761d94dcf6'), u'name': u'test', u'roles': [1.0, 9.0], u'point': 0, u'createTime': datetime.datetime(2016, 6, 23, 15, 8, 4, 130000)}

Is this behavior is expected? 

Thanks and Regards,

Samuel Feng

Luke Lovett

unread,
Jul 29, 2016, 1:02:44 PM7/29/16
to mongodb-user
Hi Samuel,

The mongo shell uses as its language Javascript, which has only a "number" type, which is a floating-point number. This is the type of all numbers, unless they're wrapped in some other BSON type like Int64 (called "NumberLong" in the shell). The shell displays floats with no significant data after the decimal as just the portion before the decimal, so "1" is the same as "1.0". Python distinguishes between ints and floats, so the type of the numbers in "roles" becomes clear using Python.

This page provides some information about types in the mongo shell: https://docs.mongodb.com/manual/core/shell-types/.
Reply all
Reply to author
Forward
0 new messages