我的查询结果一般如下:
{
'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 函数,使之快一点?
![]() | 1 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'}} ); |
![]() | 2 whahuzhihao 2016-01-26 14:21:26 +08:00 刚才试验了下。不能用'base.p1' : '$base.p1',得换个名字'base_p1':'$base.p1' 这样应该 ok |
3 billgreen1 OP @whahuzhihao 感谢,我明天上班试试 |
4 billgreen1 OP @whahuzhihao 这正是我想要的,十分感谢。 |