【问题标题】:Using the $cond statement with $project and aggregate in PyMongo在 PyMongo 中将 $cond 语句与 $project 和聚合一起使用
【发布时间】:2015-05-25 14:20:18
【问题描述】:

我想使用 pymongo 根据条件逻辑语句投影一个新字段。

如果 'status' 字段为 'successful_ended''successful_ongoing',则该值应等于 1。我尝试通过在$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'

我做错了什么?

【问题讨论】:

  • 您确定$eq 有效吗?你和'status'比,不应该是'$status'吗?
  • 是的,我也对此感到惊讶!它适用于 status$status
  • 你确定吗?因为,如果您有一个 status 字段,但想将其值与 'status' 字符串进行比较,您会怎么做?

标签: python mongodb pymongo


【解决方案1】:

请改用$or 运算符,它计算一个或多个表达式并在任何表达式为真时返回真。否则,$or 返回 false。因此successful_2 字段可以投影为:

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

【讨论】:

    【解决方案2】:

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

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

    但是,$in 仅用于常规查询。

    如果您想将一个字段值与多个值进行比较,最好使用chridam's solution

    【讨论】:

      猜你喜欢
      • 2014-04-05
      • 2020-07-04
      • 1970-01-01
      • 2021-04-11
      • 2017-07-03
      • 2015-12-03
      • 2017-08-20
      • 1970-01-01
      • 2020-04-13
      相关资源
      最近更新 更多