需要有关 Mongodb 聚合输出格式的帮助。
我的数据输入包括如下内容:
{'parent_id': '133', 'status_id': '209101162445115_1199071210114767', 'author_id': '10209422198664172', 'comment_published': '2016-08-15 08:57:09'}
在给定匹配的parent_id 的情况下,我需要计算author_ids 出现的次数。我用聚合做到了这一点:
m = collection.aggregate([{"$match": {"parent_id":"437325203079413_1543639"}},
{ "$group": {"_id": {"author_id": "$author_id"}, "count":{"$sum":1}}},
{"$project": {"_id":1, "count":1}} ]) #this line does not make any difference in the output.
page =[]
for i in m:
page.append(i)
print(page)
输出如下所示:
[{'_id': {'author_id': '10155430875324466'}, 'count': 1},
{'_id':{'author_id': '1249853341715138'}, 'count': 2},
{'_id': {'author_id': '10153804689530108'}, 'count': 1}]
我希望输出采用以下格式:
[{'author_id': '10155430875324466', 'count': 1},
{'author_id': '1249853341715138', 'count': 2},
{'author_id': '10153804689530108', 'count': 1}]
或者这个:
[{'10155430875324466', 1},
{'1249853341715138', : 2},
{'10153804689530108', 1}]
我知道在 python 中执行此操作的一种缓慢方法,但我觉得应该有更好的解决方案。是否可以在聚合查询本身中实现这一点?有人可以建议吗?
最佳答案
你可以试试这个。您可以使用author_id
作为分组_id
直接然后project
_id
中的值如author_id
进入最后阶段。
db.collection.aggregate([
{ "$match" : { "parent_id" : "437325203079413_1543639" } },
{ "$group" : { "_id" : "$author_id", "count": { "$sum" : 1 } } },
{ "$project" : { "_id" : 0, "author_id" : "$_id", "count" : 1 } }
]);
或者你可以更改最后的 $project
阶段如下图。
db.collection.aggregate([
{ "$match" : { "parent_id" : "437325203079413_1543639" } },
{ "$group" : { "_id" : { "author_id": "$author_id"}, "count": { "$sum" : 1 } } },
{ "$project" : { "_id" : 0, "author_id" : "$_id.author_id", "count":1 } }
]);
关于python - Mongodb,聚合,如何抑制_id,但保留里面的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40500283/