MongoDB aggregation pipeline $addFields with $cond - not able to use variables

Viewed 690

I am not able to use variables in the $cond in the pipeline stage. I want to add a field (processedToday inside documentPropertiesProcessed) but based on condition depending on the value of another variable postProcessingOperatorValidationCount.

The snippet of pipeline stage (as configured in python code) is as follows:

  • add flag if the document was processed today
{
    "$addFields": {
        "documentPropertiesProcessed.processedToday": {
            "$cond": [
                {"$gte":
                 [
                     "$$documentPropertiesProcessed.postProcessingOperatorValidationCount",
                     5
                 ]
                },
                "no",
                "yes"]
        }
    }
}

When executed, the error message received is as follows:

pymongo.errors.OperationFailure: Invalid $addFields :: caused by :: Use of undefined variable: documentPropertiesProcessed, full error: {'operationTime': Timestamp(1620930938, 1), 'ok': 0.0, 'errmsg': 'Invalid $addFields :: caused by :: Use of undefined variable: documentPropertiesProcessed', 'code': 17276, 'codeName': 'Location17276', '$clusterTime': {'clusterTime': Timestamp(1620930938, 1), 'signature': {'hash': b'_\x05f&\xb3\x16\xdd\x01\x00T\xe2\xa3\x04L\xa5\xd6r\x88X\x88', 'keyId': 6953591995419852803}}}

I went through the documents and questions but still not able to understand as to where the issue lies. The variables are very much present. Any pointers and guidelines will be very helpful.

1 Answers

I believe you are attempting to achieve an if-then-else block in conventional coding terms? If that is the case you will have to do the following ( please note that I havent checked for the syntax and this is just a sample

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

check this link as well : [https://stackoverflow.com/questions/27479347/is-there-an-elseif-thing-in-mongodb-to-cond-while-aggregating]

Related