我的查询结果一般如下:
{
'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 函数,使之快一点?
