demo 數(shù)據(jù)
{
{'_id': ObjectId('61cbd33850ada9fbdc600812'),
'pid': 1,
'other': 2,
'uid': 888},
{'_id': ObjectId('61cbd36750ada9fbdc600824'),
'pid': 1,
'other': 3,
'uid': 998},
{'_id': ObjectId('61cbd37550ada9fbdc600832'),
'pid': 2,
'other': 7,
'uid': 22},
{'_id': ObjectId('61cbd38750ada9fbdc600837'),
'pid': 3,
'other': 5,
'uid': 87},
{'_id': ObjectId('61cbd39050ada9fbdc60083a'),
'pid': 3,
'other': 7,
'uid': 12},
{'_id': ObjectId('61cbd46a50ada9fbdc60086a'),
'pid': 3,
'other': 22222,
'uid': 35}
}
查詢
查詢1
a=client.mytest.test1.aggregate(
[
{
"$group":{
"_id":"$pid",
"other":{
"$last":"$other"
},
"uid":{
"$last":"$uid"
}
}
},
{
"$sort":{
"other":1
}
}
]
)
結(jié)果
[
{'_id': 1, 'other': 3, 'uid': 998},
{'_id': 2, 'other': 7, 'uid': 22},
{'_id': 3, 'other': 22222, 'uid': 35}
]
查詢2
a=client.mytest.test1.aggregate(
[
{
"$group":{
"_id":"$pid",
"other":{
"$last":"$other"
}
},
{
"$sort":{
"other":1
}
}
]
)
結(jié)果
[{'_id': 1, 'other': 3}, {'_id': 2, 'other': 7}, {'_id': 3, 'other': 22222}]
查詢3
先按 other 倒序排列拧廊,再按 pid 分組取每組的最后一個 other
a=client.mytest.test1.aggregate(
[
{
"$sort":{
"other":-1
}
},
{
"$group":{
"_id":"$pid",
"other":{
"$last":"$other"
}
}
]
)
結(jié)果
[{'_id': 1, 'other': 2}, {'_id': 2, 'other': 7}, {'_id': 3, 'other': 5}]
分析
先倒序
[{'_id': ObjectId('61cbd46a50ada9fbdc60086a'),
'pid': 3,
'other': 22222,
'uid': 35},
{'_id': ObjectId('61cbd37550ada9fbdc600832'),
'pid': 2,
'other': 7,
'uid': 22},
{'_id': ObjectId('61cbd39050ada9fbdc60083a'),
'pid': 3,
'other': 7,
'uid': 12},
{'_id': ObjectId('61cbd38750ada9fbdc600837'),
'pid': 3,
'other': 5,
'uid': 87},
{'_id': ObjectId('61cbd36750ada9fbdc600824'),
'pid': 1,
'other': 3,
'uid': 998},
{'_id': ObjectId('61cbd33850ada9fbdc600812'),
'pid': 1,
'other': 2,
'uid': 888}]
再分組课兄,取每組最后一個
util
查詢 1和 2,是先按pid分組藏古,再查每組最后一條增炭,得出結(jié)果A,最后在對A里的other字段進(jìn)行排序
查詢3拧晕,是先按other字段排序隙姿,再根據(jù)排序結(jié)果進(jìn)行分組取每組最后一條數(shù)據(jù)。
注意:分組后厂捞,每組內(nèi)的數(shù)據(jù)输玷,會保持之前的順序排列。