mongodb 如何返回平的 dict?

2016-01-26 12:46:35 +08:00
 billgreen1

我的查询结果一般如下:
{
'year':2015,
‘ a ’:1,
'base': {'p1': 15}
....
}

目标是

{
'year':2015,
‘ a ’:1,
'base.p1':15
....
}

我现在用的是自定义一个 flatten_dict 函数

def flatten(d, parent_key='', sep='.'):
    """
    字典 flatten
    """
    items = []
    for k, v in d.items():
        new_key = parent_key + sep + k if parent_key else k
        if isinstance(v, MutableMapping):
            items.extend(flatten(v, new_key, sep=sep).items())
        else:
            items.append((new_key, v))
    return dict(items)

但是太慢,因为大概有 3w+个这样的小的结果。 line_profile 显示

isinstance(v, MutableMapping)

占用了 60%的时间。

我的想法是 mongodb 能否直接返回一个平的 dict ?
因为查询的时候这样指定是可以的'base.p1':{'$gt':15}

或者,通过修改 flatten 函数,使之快一点?

3764 次点击
所在节点    MongoDB
4 条回复
whahuzhihao
2016-01-26 14:14:04 +08:00
什么叫平的 dict ?
如果要求 base 字段不是数组 而是一个自定义键值对的话,可以用 aggregate 聚合方法里的 project 管道将结果重新格式化一遍 。如下:
db.xxx.aggregate( {$project : { 'year':1,'a':1,'base.p1':'$base.p1'}} );
whahuzhihao
2016-01-26 14:21:26 +08:00
刚才试验了下。不能用'base.p1' : '$base.p1',得换个名字'base_p1':'$base.p1' 这样应该 ok
billgreen1
2016-01-26 20:39:33 +08:00
@whahuzhihao 感谢,我明天上班试试
billgreen1
2016-01-27 22:27:33 +08:00
@whahuzhihao 这正是我想要的,十分感谢。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/253434

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX