【问题标题】:insert and query an OrderedDict in MongoHQ在 MongoHQ 中插入和查询 OrderedDict
【发布时间】:2014-01-06 22:21:25
【问题描述】:

在成功将 OrderedDict 对象插入 MongoHQ 后,我尝试通过 PyMongo 的 collection.find_one() 命令查询相同的 OrderedDictionary。这失败了,密钥的顺序丢失了。字典变成普通字典。

我的代码如下所示:

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')}

你们能帮帮我吗?非常感谢。

【问题讨论】:

  • 已解决:db_conn = pymongo.Connection('mongodb://*:*@*.mongohq.com:*/testDatabase', document_class= collections.OrderedDict)

标签: pymongo mongohq ordereddictionary


【解决方案1】:

也许你想试试

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

【讨论】:

    猜你喜欢
    • 2014-12-03
    • 1970-01-01
    • 2013-10-10
    • 2014-09-01
    • 1970-01-01
    • 2018-05-16
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多