【问题标题】:Ordered attributes in retrieving documents from mongo with pymongo?使用 pymongo 从 mongo 检索文档时的有序属性?
【发布时间】:2012-08-15 05:53:42
【问题描述】:

当我将以下文档存储到 mongo 中时,类似于:

{
name: Somename,
profile: Someprofile
}

当我使用 find_one() 时:

我得到如下结果:

{
profile: Someprofile,
_id: 35353432326532(random mongo id),
name: Somename
}

在 python 中是否有某种方式,当我在 find_one 之前或之后做某事时,我可以得到一个 json 字符串的结果,该字符串的排序如下:

{
_id: 35353432326532(random mongo id),
name: Somename,
profile: Someprofile
}

我尝试使用如下所示的 OrderedDict,但似乎没有帮助。

somedocument = db.mycollection
theordereddict = OrderedDict(data_layer.find_one())
print str(theordereddict)

关于属性,我如何以正确的顺序获取我的输出字符串?在我将文档插入数据库之前,这个顺序是由其他东西决定的吗?

【问题讨论】:

标签: python mongodb


【解决方案1】:

collections.OrderedDict 不会对键进行排序,它只是保留顺序,您需要按照要检索它们的顺序将键插入其中。

d = data_layer.find_one()
def key_function(tuple):
    """This defines the sort order for the sorted builtin"""
    return tuple[0]
sorted_dict = collections.OrderedDict((k,v) for k, v in sorted(d.items(),
                                                               key=key_function))     

也就是说,print str(sorted_dict) 似乎没有给你想要的输出。我认为您需要手动构建排序的字符串表示形式。例如:

s = "{" + ",".join(["%s:%s" for k,v in sorted(d.items(), key=key_function)]) + "}"

【讨论】:

  • 什么是“lambda”及其后面的语法?
  • lambda 在我更新的答案中定义了一个等效于key_function 的匿名函数。重要的部分是使用一个函数来自定义 sorted 内置执行的排序。
【解决方案2】:

与@Mike Steder 的回答基本相同,但可能不那么花哨且更清晰:

import json
from collections import OrderedDict

theordereddict = OrderedDict()
d = data_layer.find_one()
for k in sorted(d.keys()):
    theordereddict[k] = d[k]

json.dumps(theordereddict)

【讨论】:

    猜你喜欢
    • 2015-11-18
    • 2015-11-02
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-15
    相关资源
    最近更新 更多