如何在pymongo中获得有序词典? [英] How to get ordered dictionaries in pymongo?

查看:118
本文介绍了如何在pymongo中获得有序词典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在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 选项。

这里是一个示例:

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中获得有序词典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆