Using $ cond operator with $ project and aggregate in PyMongo

I want to design a new field based on a conditional boolean expression using pymongo.

The value must be 1 if the status field is "success_ended" or "success_ongoing". I tried to implement this using $in

in instructions $cond

. A simplified version of my aggregate operator looks like this:

pipeline = [
    {'$project': {'platform':1, 'platform_id':1, 'funding_type':1, 'raised_usd':1, 'status':1, 
                  'successful_1': # an equals statement works
                     {
                        '$cond':[{'$eq':['status', 'successful_ended']}, 1, 0]
                     },
                  'successful_2': # but this fails 
                     {
                        '$cond':[{'status': {'$in': ['successful_ended', 'successful_ongoing']}}, 1, 0]
                     }
                  }
    }
]

result = db.projects.aggregate(pipeline)

      

And it doesn't work with the message:

invalid operator '$in'

      

What I did wrong?

+3


source to share


2 answers


Instead, use one that evaluates one or more expressions and returns true if any of the expressions are true. Returns false otherwise . Thus, the field can be designed as: $or

$or

successful_2



'successful_2': {
    '$cond': [ 
        { 
            '$or': [ 
                { '$eq': [ '$status', 'successful_ended' ] }, 
                { '$eq': [ '$status', 'successful_ongoing' ] } 
            ]
        }     
        , 1, 0 
    ]
}

      

+3


source


The problem is that no operator is defined for the aggregation structure $in

.

As you can see, there are separate operators $eq

defined for normal query and aggregate query , and their syntax is different.



However, it $in

is only defined for a regular request.

If you want to compare a field value with multiple values, it is better to go to chridam's solution

+1


source







All Articles