[英]Using the $cond statement with $project and aggregate in PyMongo
I want to project a new field based on a conditional logic statement, using pymongo. 我想使用pymongo基于条件逻辑语句来设计一个新字段。
The value should equal 1 if the 'status' field is either 'successful_ended' or 'successful_ongoing' . 如果'status'字段是'successful_ended'或'successful_ongoing',则该值应该等于1。 I've tried implementing this by using
$in
within a $cond
statement. 我试过在
$cond
语句中使用$in
来实现这个。 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. 使用
$or
运算符来计算一个或多个表达式,如果任何表达式为真,则返回true。 Otherwise, $or
returns false. 否则,
$or
返回false。 Thus the successful_2
field can be projected as: 因此,
successful_2
字段可以预测为:
'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. 问题是没有为聚合框架定义
$in
运算符。
As you can see there are separate $eq
operators defined for a regular query and aggregation query , and their syntax is different. 如您所见,为常规查询和聚合查询定义了单独的
$eq
运算符,并且它们的语法不同。
However $in
is defined only for a regular query. 但是
$in
仅定义为常规查询。
If you want to compare a field value against multiple values, you better go with chridam's solution 如果要将字段值与多个值进行比较,最好使用chridam的解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.