在 PyMongo 中将 $cond 语句与 $project 和聚合一起使用

Using the $cond statement with $project and aggregate in PyMongo

我想使用 pymongo 投影一个基于条件逻辑语句的新字段。

如果 'status' 字段是 'successful_ended',则该值应等于 1 ]'successful_ongoing'。我尝试通过在 $cond 语句中使用 $in 来实现这一点。我的聚合语句的简化版本是这样的:

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)

它失败并显示消息:

invalid operator '$in'

我做错了什么?

问题是没有为聚合框架定义 $in 运算符。

如您所见,为 regular query and aggregation query 定义了单独的 $eq 运算符,并且它们的语法不同。

但是 $in 仅为常规查询定义。

如果要将一个字段值与多个值进行比较,最好使用

使用$or operator instead which evaluates one or more expressions and returns true if any of the expressions are true. Otherwise, $or returns false。因此 successful_2 字段可以投影为:

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