带有 $cond 的 MongoDB 聚合管道 $addFields - 无法使用变量

Posted

技术标签:

【中文标题】带有 $cond 的 MongoDB 聚合管道 $addFields - 无法使用变量【英文标题】:MongoDB aggregation pipeline $addFields with $cond - not able to use variables 【发布时间】: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 所有这些都被屏蔽了。 【参考方案1】:

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

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

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

【讨论】:

以上是关于带有 $cond 的 MongoDB 聚合管道 $addFields - 无法使用变量的主要内容,如果未能解决你的问题,请参考以下文章

在 Mongodb/Mongoose 聚合中的子集中应用 $cond

MongoDB,如何将查找和排序与聚合中的 $cond 结合起来?

MongoDB,如何将查找和排序与聚合中的 $cond 结合起来?

if else if cond in mongodb 聚合

为啥在与数组中的字段匹配时,mongoDB聚合中的查找中的管道不起作用?

翻译MongoDB指南/聚合——聚合管道