python - Mongodb,聚合,如何抑制_id,但保留里面的内容?

标签 python mongodb aggregation-framework

需要有关 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/

相关文章:

Python doctest 不能在名为 signal.py 的文件上运行

javascript - JavaScript 中的数组理解?

python - 消除 fft 图表中的噪音

javascript - 具有多个值的 Mongo $addToSet 语法正确

node.js - 将 Small Parse ID 迁移到普通 MongoDB 的 ObjectID

mongodb - 如何在 mongodb 聚合中使用 $geoNear 和 $lookup

javascript - 类型错误 : Cannot call method 'toArray' of undefined while aggregatein mongo in node. js

mongodb - 如何在每个组中选择最大项目?

python - 如何在Python中加入列表的相应元素

node.js - 唯一和稀疏模式级索引 MongoDB 和 Mongoose