【问题标题】:MongoDB aggregation pipeline $addFields with $cond - not able to use variables带有 $cond 的 MongoDB 聚合管道 $addFields - 无法使用变量
【发布时间】:2021-08-04 07:24:55
【问题描述】:

我无法在管道阶段的$cond 中使用变量。我想添加一个字段(processedTodaydocumentPropertiesProcessed),但基于条件取决于另一个变量 postProcessingOperatorValidationCount 的值。

pipeline阶段的sn-p(在python代码中配置)如下:

  • 如果今天处理了文档,则添加标志
{
    "$addFields": {
        "documentPropertiesProcessed.processedToday": {
            "$cond": [
                {"$gte":
                 [
                     "$$documentPropertiesProcessed.postProcessingOperatorValidationCount",
                     5
                 ]
                },
                "no",
                "yes"]
        }
    }
}

执行时收到的错误信息如下:

pymongo.errors.OperationFailure: Invalid $addFields :: 由 :: 使用未定义的变量: documentPropertiesProcessed, 完全错误: {'operationTime': Timestamp(1620930938, 1), 'ok': 0.0, 'errmsg': '无效的 $addFields :: 由 :: 使用未定义的变量:documentPropertiesProcessed','code':17276,'codeName':'Location17276','$clusterTime':{'clusterTime':Timestamp(1620930938, 1),'签名': {'hash': b'_\x05f&\xb3\x16\xdd\x01\x00T\xe2\xa3\x04L\xa5\xd6r\x88X\x88', 'keyId': 6953591995419852803}}}

我浏览了文件和问题,但仍然无法理解问题所在。变量非常存在。任何指示和指南都会非常有帮助。

【问题讨论】:

  • 使用单个美元符号而不是 2。"$documentPropertiesProcessed.postProcessingOperatorValidationCount"
  • 删除了一个 $ 并执行了管道。错误已消失,但未根据比较结果设置字段值。所有值都设置为“否”。现在 $gte 没有生效。
  • 请分享示例源数据、预期输出和您的代码 sn-p 所有这些都被屏蔽了。

标签: mongodb aggregation-framework pymongo


【解决方案1】:

我相信您正试图以传统的编码术语实现 if-then-else 块?如果是这种情况,您将必须执行以下操作(请注意,我没有检查语法,这只是一个示例

`"$cond": { 
        "if": { "$gt": [ "$$documentPropertiesProcessed.postProcessingOperatorValidationCount", "5" ] }, 
        "then": $date,
        "else": ''
          }`

也检查此链接:[https://stackoverflow.com/questions/27479347/is-there-an-elseif-thing-in-mongodb-to-cond-while-aggregating]

【讨论】:

    猜你喜欢
    • 2020-12-30
    • 2019-04-07
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多