PyMongo group by:迭代组
PyMongo group by: iterate over groups
我希望遍历通过 Mongo 的聚合获得的组。
例如,以下将从集合中打印字段 field_name
的不同值:
collection = db['collection']
for entry in collection.aggregate([{'$group':{'_id':'$field_name'}}]):
print entry
但是,它不允许我遍历不同的条目组。
使用 Pandas 数据框我会这样做,假设数据框 df
代表 collection
:
gb = df.groupby(['field_name'])
for ix, df_g in enumerate([gb.get_group(x) for x in gb.groups]):
print df_g
这样df_g
就是每组对应的dataframe。在 PyMongo 中是否有相应的 get_group
函数可用,这将 return 一个仅包含当前组的游标?
我想我可以通过聚合获得 field_name
的不同值,然后分别查询每个组,但我希望避免这些单独的查询。
你需要添加一些accumulators to the pipeline, e.g. $push
collection = db['collection']
for entry in collection.aggregate([{'$group':{'_id':'$field_name'}, docs: {$push:"$$ROOT}}]):
print entry["docs"]
请记住单个“项目”cannot exceed 16MB in BSON format,因此如果 field_name
中有许多文档共享相同的值,或者文档足够大,或者两者都足够大,您可能会遇到错误您不能将更多文档 $push 到列表中。
在这种情况下,您将只需要 $push 文档的必需部分而不是 $$ROOT
,例如
collection = db['collection']
for entry in collection.aggregate([{'$group':{'_id':'$field_name'}, docs: {$push:{
_id: "$_id",
one_field:"$one_field",
another_field: "$another_field"
}}}]):
print entry["docs"]
将仅打印分组文档中的 3 个选定字段
我希望遍历通过 Mongo 的聚合获得的组。
例如,以下将从集合中打印字段 field_name
的不同值:
collection = db['collection']
for entry in collection.aggregate([{'$group':{'_id':'$field_name'}}]):
print entry
但是,它不允许我遍历不同的条目组。
使用 Pandas 数据框我会这样做,假设数据框 df
代表 collection
:
gb = df.groupby(['field_name'])
for ix, df_g in enumerate([gb.get_group(x) for x in gb.groups]):
print df_g
这样df_g
就是每组对应的dataframe。在 PyMongo 中是否有相应的 get_group
函数可用,这将 return 一个仅包含当前组的游标?
我想我可以通过聚合获得 field_name
的不同值,然后分别查询每个组,但我希望避免这些单独的查询。
你需要添加一些accumulators to the pipeline, e.g. $push
collection = db['collection']
for entry in collection.aggregate([{'$group':{'_id':'$field_name'}, docs: {$push:"$$ROOT}}]):
print entry["docs"]
请记住单个“项目”cannot exceed 16MB in BSON format,因此如果 field_name
中有许多文档共享相同的值,或者文档足够大,或者两者都足够大,您可能会遇到错误您不能将更多文档 $push 到列表中。
在这种情况下,您将只需要 $push 文档的必需部分而不是 $$ROOT
,例如
collection = db['collection']
for entry in collection.aggregate([{'$group':{'_id':'$field_name'}, docs: {$push:{
_id: "$_id",
one_field:"$one_field",
another_field: "$another_field"
}}}]):
print entry["docs"]
将仅打印分组文档中的 3 个选定字段