【问题标题】:MongoDB $group where value is no null值不为空的 MongoDB $group
【发布时间】:2020-07-19 13:37:55
【问题描述】:

我有一个以这种格式存储成绩单的集合:

{
 convId: abcd,
 timestamp: 2020-02-08T15:43,
 source: { channel: 'channel1' }
},
{
 convId: abcd,
 timestamp: 2020-02-08T15:42,
 source: { channel: 'channel1' }
},
{
 convId: abcd,
 timestamp: 2020-02-08T15:41,
 source: { channel: null }
},

某些记录的 source.channel 字段为空。当我使用聚合管道获取其中一些的唯一对话时,我将 source.channel 设为 null,这是一个问题。我在下面使用 $小组赛:

$group: {
 _id: '$convId',
 started: { $min: '$timestamp' },
 ended: { $max: '$timestamp' },
 channel: { $first: '$source.channel' },
}

我知道这是因为 $first 的问题,所以我尝试使用 $min 和 $max(以及其他聚合运算符),因为它们应该忽略空值,但它不会因为未知原因(至少 1文档的 source.channel 字段填充不为空)。

谁能建议我如何排除 null 并返回带有值的字段?

编辑:我需要所有文档的时间戳,因此我无法在 $match 中对其进行优化。

【问题讨论】:

    标签: mongodb mongodb-query nosql aggregation-framework


    【解决方案1】:

    你可以检查变量是否为空值,如果它不为空你可以返回值,否则为空。

    $group: {
     _id: '$convId',
     started: { $min: '$timestamp' },
     ended: { $max: '$timestamp' },
     channel: { $cond: {
    if: {
    $ne: [ "$source.channel", null ]
    }, then: "$source.channel", else: 'your_value'
    } },
    }
    

    【讨论】:

    • 感谢您的回复。但是,“通道”值是动态的,因此我需要将“其他”设置为不为空的文档值。有可能吗?
    猜你喜欢
    • 2023-04-11
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多