demo 数据
{
{'_id': ObjectId('61cbd33850ada9fbdc600812'), 'pid': 1, 'other': 2},
{'_id': ObjectId('61cbd36750ada9fbdc600824'), 'pid': 1, 'other': 3},
{'_id': ObjectId('61cbd37550ada9fbdc600832'), 'pid': 2, 'other': 7},
{'_id': ObjectId('61cbd38750ada9fbdc600837'), 'pid': 3, 'other': 5},
{'_id': ObjectId('61cbd39050ada9fbdc60083a'), 'pid': 3, 'other': 7},
{'_id': ObjectId('61cbd46a50ada9fbdc60086a'), 'pid': 3, 'other': 22222}
}
按 pid 分组,计算每组都有几条数据
肉眼可见
pid=1 2条
pid=2 1条
pid=3 3条
聚合方法
a=client.mytest.test1.aggregate(
[
{
"$group":{
"_id":"$pid",
"count":{
"$sum":1
}
}
}
]
)
结果
list(a)
[{'_id': 3, 'count': 3}, {'_id': 2, 'count': 1}, {'_id': 1, 'count': 2}]
_id
即 pid
,可以看到 pid=3 count为3,pid=2 count为1,pid=1 count为2,
网友评论