I want to project a new field based on a conditional logic statement, using pymongo.
The value should equal 1 if the 'status' field is either 'successful_ended' or 'successful_ongoing' . I've tried implementing this by using $in
within a $cond
statement. A simplified version of my aggregate statement is like so:
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 fails with the message:
invalid operator '$in'
What have I done wrong?
Use the $or
operator instead which evaluates one or more expressions and returns true if any of the expressions are true. Otherwise, $or
returns false. Thus the successful_2
field can be projected as:
'successful_2': {
'$cond': [
{
'$or': [
{ '$eq': [ '$status', 'successful_ended' ] },
{ '$eq': [ '$status', 'successful_ongoing' ] }
]
}
, 1, 0
]
}
The problem is that there is no $in
operator defined for the aggregation framework.
As you can see there are separate $eq
operators defined for a regular query and aggregation query , and their syntax is different.
However $in
is defined only for a regular query.
If you want to compare a field value against multiple values, you better go with chridam's solution
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.