【发布时间】:2021-03-22 23:36:01
【问题描述】:
我有一个包含 type 的事件集合,可以是 0、1、2、3、4、5 和 createdAt 日期。每个事件都与另一个称为 RTS 的集合相关。
我想为每个 Rts 收集每个类型的最后一个事件。
使用我的解决方案时遇到问题:
问题是,我必须一一描述每个types 才能使其正常工作。是否有任何解决方案可以通过type 值诱导动态密钥创建?
这是我现在得到的:
- 我对数据进行排序
- 按
idRTS分组,其中包含指向第二个集合的链接。对于每种类型,将值推送到特定数组中。 - 从类型数组中删除空值。
- 只保留第一个值
(the most updated)。 - 使数据可呈现。
[
{
$sort: {
idRTS: -1,
createdAt: -1
}
},
{
$group: {
_id: '$idRTS',
type0: {
$push: {
$cond: {
if: {
$eq: [
'$type', 0
]
},
then: '$$ROOT',
else: null
}
}
},
type5: {
$push: {
$cond: {
if: {
$eq: [
'$type', 5
]
},
then: '$$ROOT',
else: null
}
}
}
}
},
{
$project: {
_id: '$_id',
type0: {
'$filter': {
'input': '$type0',
'as': 'd',
'cond': {
'$ne': [
'$$d', null
]
}
}
},
type5: {
$filter: {
input: '$type5',
as: 'd',
cond: {
$ne: [
'$$d', null
]
}
}
}
}
},
{
$project: {
_id: '$_id',
type0: {
$arrayElemAt: [
'$type0', 0
]
},
type5: {
'$arrayElemAt': [
'$type5', 0
]
}
}
}
]
【问题讨论】:
标签: node.js mongodb mongoose aggregate