对 object 的数组进行排序,然后对 collection 的数组进行排序
sort array of object, then sort array of collection
这里是 collection 和查询 code。现在我想做两件事。
i) sort reportTypes
array objects by counts
in descending order 然后,
ii) 排序 collection by 总数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
}
]
}
]
也许是这样的:
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
}
}
])
解释:
- 展开 reportTypes
- 按 managerId 排序并按 reportTypes.count
降序
- 组与推送形成相同的对象,每个 managerId 排序数组并生成每个 managerId 的摘要计数。
- addFileds managerId
- 按总计数 (cnt) 排序
- 只投影需要的字段
这里是 collection 和查询 code。现在我想做两件事。
i) sort reportTypes
array objects by counts
in descending order 然后,
ii) 排序 collection by 总数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
}
]
}
]
也许是这样的:
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
}
}
])
解释:
- 展开 reportTypes
- 按 managerId 排序并按 reportTypes.count 降序
- 组与推送形成相同的对象,每个 managerId 排序数组并生成每个 managerId 的摘要计数。
- addFileds managerId
- 按总计数 (cnt) 排序
- 只投影需要的字段