Вопрос

After successfully inserting an OrderedDict object in to MongoHQ, i try to query the same OrderedDictionary by the collection.find_one() command of PyMongo. This fails, the order of the keys are lost. The dictonary becomes an ordinary dictonary.

My code looks like this:

import collections
import pymongo

test = collections.OrderedDict()
test.update({'test1': 1})
test.update({'test2': 2})
test.update({'test3': 3})
test.update({'test4': 4})
test.update({'test5': 5})
test
>>>OrderedDict([('test1', 1), ('test2', 2), ('test3', 3), ('test4', 4), ('test5', 5
)])

db_conn = pymongo.Connection('mongodb://*:*@*.mongohq.com:*/testDatabase')
db_conn.testDatabase['testCollection'].insert(test)
test_new = db_conn.testDatabase['testCollection'].find_one()

print test_new
>>> {u'test1': 1, u'test3': 3, u'test2': 2, u'test5': 5, u'test4': 4, u'_id': Object
Id('52cc777b92c49c146cb5e3db')}

Could you guys help me out? Thanks a lot.

Это было полезно?

Решение

Maybe you want to try

test_new = db_conn.testDatabase['testCollection'].find_one(as_class=collections.OrderedDict)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top