這是收集和查詢代碼。現在我想做兩件事。
i)然后按降序對陣列物件進行排序 ,reportTypescounts
ii)按總數對集合進行排序。陣列中的計數按降序排列。reportTypes
iii) 然后分組managerId
我希望結果檔案喜歡這個。
[
{
"_id": ObjectId("62441917d12596f96de163a3"),
"managerId": 2,
"reportTypes": [
{
"reasonId": 100,
"count": 20
}
]
},
{
"_id": ObjectId("62441917d12596f96de163a5"),
"managerId": 3,
"reportTypes": [
{
"reasonId": 200,
"count": 10
},
{
"reasonId": 100,
"count": 5
},
{
"reasonId": 300,
"count": 0
}
]
},
{
"_id": ObjectId("62441917d12596f96de163a2"),
"managerId": 1,
"reportTypes": [
{
"reasonId": 300,
"count": 4
},
{
"reasonId": 200,
"count": 3
},
{
"reasonId": 100,
"count": 2
}
]
}
]
uj5u.com熱心網友回復:
也許是這樣的:
db.collection.aggregate([
{
$unwind: "$reportTypes"
},
{
$sort: {
"managerId": 1,
"reportTypes.count": -1
}
},
{
$group: {
_id: "$managerId",
reportTypes: {
$push: "$reportTypes"
},
cnt: {
$sum: "$reportTypes.count"
}
}
},
{
$addFields: {
managerId: "$_id"
}
},
{
$sort: {
cnt: -1
}
},
{
$project: {
managerId: 1,
reportTypes: 1
}
}
])
解釋:
- 展開報告型別
- 按 managerId 排序,按 reportTypes.count 降序
- 使用 push 進行分組以形成具有每個 managerId 排序陣列的相同物件,并為每個 managerId 生成匯總計數。
- addFileds managerId
- 按總數排序 (cnt)
- 僅投影所需的欄位
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/455203.html
