我有两个集合,具有以下结构和数据
Trx集合
id | trxid | subitem | clazz
1 | 100 | 1 | A
2 | 100 | 2 | A
3 | 100 | 3 | B
4 | 200 | 1 | B
班级收藏
id | clazz | applicable
1 | A | y
2 | B | n
我正在寻找按 trxid 分组的输出,以及子项目的计数以及适用和不适用的子项目的计数。例如,对于上面输出的数据
trxid | subitem count | applicable sub items count | non-applicable sub items count
100 | 3 | 2 | 1
200 | 1 | 0 | 1
我已经让子项目计数工作。我查看了“$lookup”,但不确定如何通过适用和不适用的子项计数来映射此计数,如上所示。任何指向上述的指针都受到高度赞赏。
编辑:
集合中有 8000 多个文档,但以下查询仅返回一个子集。
db.trx.aggregate( [ { $group : { _id : "$trxid", count: { $sum : 1 } } } ])
[
{ _id: 'Trx100', count: 1 },
{ _id: 'Trx101', count: 1 },
{ _id: 'Trx102', count: 6 },
{ _id: 'Trx103', count: 5 },
{ _id: 'Trx104', count: 2 },
{ _id: 'Trx105', count: 2 },
{ _id: 'Trx106', count: 1 },
{ _id: 'Trx107', count: 1 },
{ _id: 'Trx108', count: 7 },
{ _id: 'Trx109', count: 26 },
{ _id: 'Trx110', count: 18 },
{ _id: 'Trx111', count: 5 },
{ _id: 'Trx112', count: 15 },
{ _id: 'Trx113', count: 1 },
{ _id: 'Trx114', count: 8 }
]
您可以使用管道方法来获取您想要的组。
https://mongoplayground.net/p/3NfMUJrXVbS
db.trx.aggregate([
{
$group: {
_id: {
clazz: "$clazz",
trxid: "$trxid"
},
total: {$sum: 1},
}
},
{
$lookup: {
from: "classes",
as: "clazz",
let: {clazzName: "$_id.clazz"},
pipeline: [
{$match: {
$expr: {$eq: ["$$clazzName", "$clazz"]}
}},
{$project: {
applicable: {$eq: ["$applicable", "y"]}
}}
]
}
},
{
$group: {
_id: "$_id.trxid",
subitemCount: {$sum: "$total"},
applicableCount: {
$sum: {
$cond: [
{$eq: [{$arrayElemAt: ["$clazz.applicable", 0]}, true]},
'$total',
0
]
}
},
nonApplicableCount: {
$sum: {
$cond: [
{$eq: [{$arrayElemAt: ["$clazz.applicable", 0]}, false]},
'$total',
0
]
}
}
}
}
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句