问题描述
我正在尝试在 Pymongo 中获取有序字典.我读过它可以用 bson.son.Son 来完成.文档在这里
I am trying get ordered dictionaries in Pymongo. I have read it can be done with bson.son.Son. The Docs are Here
但是,我似乎无法让它发挥作用.谷歌上关于它的内容并不多.有一些关于首先配置 pymongo 以告诉它使用 SON 对象的讨论,但没有示例.一位朋友建议您在查找时传递一个参数.他不记得了.
However, I can't seem to make it work. There is not much on google about it. There are some discussions on configuring pymongo first to tell it to use SON objects but no examples. A friend suggested passing a param when you do a find. He couldn't remember.
我能够创建 SON 对象.但是当它们被插入到数据库中然后又出来时,它们只是普通的字典.
I'm able to create the SON objects. But when they get inserted into the DB and then come back out they are just plain dicts.
我真的不确定要给你什么代码示例,因为我真的不知道从哪里开始.每次添加新用户时,以下代码段都会创建一个空的 SON 对象.'sub_users' 对象也是用 SON 创建的.当我从数据库中读取帐户文档时,它们只是普通的 Python 字典.
I'm not sure really what code example to give you because I really don't know where to start. The below snippet creates an empty SON object every time I add a new user. The 'sub_users' object was also created with SON. When I read the account document back from the DB they are just normal python dicts.
account['sub_users'][sub_user_name] = bson.SON()
with mongo_manager.Collection(CFG.db, 'Users') as users:
users.save(account)
也许是一个过去的参数来配置这样的发现?这是我朋友的建议,但他不记得了.
Maybe a param past to the find like this to configure? This was my friends suggestion but he could not remember.
with mongo_manager.Collection(CFG.db, 'Users') as users:
account = users.find_one({'_id': _id, 'DOC':'OrderedDict})
有什么想法吗?
推荐答案
您可以使用 bson.son.SON
或 OrderedDict
来存储有序字典.
You can use bson.son.SON
or OrderedDict
to store ordered dict.
并使用 as_class=OrderedDict
选项检索数据.
And retrive data with as_class=OrderedDict
option.
这是一个例子:
from collections import OrderedDict
from pymongo import MongoClient
import bson
client = MongoClient()
sample_db = client['sample']
test_col = sample_db['test']
test_col.drop()
data = OrderedDict([("one", 1), ("two", 2), ("three", 3), ("four", 4)])
test_col.insert(data)
print(list(test_col.find({}, {'_id': 0}, as_class=OrderedDict)))
test_col.drop()
data = bson.son.SON([("one", 1), ("two", 2), ("three", 3), ("four", 4)])
test_col.insert(data)
print(list(test_col.find({}, {'_id': 0}, as_class=OrderedDict)))
输出:
[OrderedDict([(u'one', 1), (u'two', 2), (u'three', 3), (u'four', 4)])]
[OrderedDict([(u'one', 1), (u'two', 2), (u'three', 3), (u'four', 4)])]
这篇关于如何在 pymongo 中获取有序字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!