demo 數(shù)據(jù)
{
{'_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 分組逐抑,計算每組都有幾條數(shù)據(jù)
肉眼可見
pid=1 2條
pid=2 1條
pid=3 3條
聚合方法
a=client.mytest.test1.aggregate(
[
{
"$group":{
"_id":"$pid",
"count":{
"$sum":1
}
}
}
]
)
結(jié)果
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进每,