如何解决Mongodb groupby和查找/加入
我有两个集合,具有以下结构和数据
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',{ _id: 'Trx102',count: 6 },{ _id: 'Trx103',count: 5 },{ _id: 'Trx104',count: 2 },{ _id: 'Trx105',{ _id: 'Trx106',{ _id: 'Trx107',{ _id: 'Trx108',count: 7 },{ _id: 'Trx109',count: 26 },{ _id: 'Trx110',count: 18 },{ _id: 'Trx111',{ _id: 'Trx112',count: 15 },{ _id: 'Trx113',{ _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",false]},0
]
}
}
}
}
])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。