简体   繁体   English

如何在 pymongo 中进行条件搜索?

[英]how can I do a conditional search in pymongo?

I am trying to make a conditional query.我正在尝试进行条件查询。 I want to search in the whole collection those documents that fit in range of prices of 25% and if the documents has a particular field(in this case 'audiPrice') I will use this field to do my search, and if this document hasn't the field, I will use a 'price' field我想在整个集合中搜索那些符合 25% 价格范围的文档,如果这些文档具有特定字段(在本例中为“audiPrice”),我将使用该字段进行搜索,如果该文档没有't 字段,我将使用 'price' 字段

I have search in the mongodb documentation( https://docs.mongodb.com/manual/reference/operator/aggregation/cond/ ) and found the operator $cond and I have try to make a the query as you can see我在 mongodb 文档中进行了搜索( https://docs.mongodb.com/manual/reference/operator/aggregation/cond/try to make a query as $cond /cond/)并找到了

pipeline = [
    {
        '$cond': {
            'if': {'audiPrice': {'$exists': True}}, 'then': {'$match':
                {'audiPrice': {
                    '$lte': price * 1.75, '$gte': price * 0.25
            }
                }
            },'else': {'$match': {
                'price': {
                    '$lte': price * 1.75, '$gte': price * 0.25
            }
            }


        }

    }
    }

]

and I got this error message我收到了这个错误信息

pymongo.errors.OperationFailure: Unrecognized pipeline stage name: '$cond'

Do you know how could I achieve my goal?你知道我怎样才能实现我的目标吗?

I am using python and pymongo.我正在使用 python 和 pymongo。

thanks谢谢

You can use cond in $project or $expr in $match stage as:您可以在 $project 中使用 cond 或在 $match 阶段使用 $expr :

collectionName.aggregate([
  {
    $match: {
      $expr: {
        $cond: {
          if: {
            $gt: [
              "$audiPrice",
              null
            ]
          },
          then: {
            $and: [
              {
                $gte: [
                  "$audiPrice",
                  price * 0.25
                ]
              },
              {
                $lte: [
                  "$audiPrice",
                  price * 1.75
                ]
              }
            ]
          },
          else: {
            $and: [
              {
                $gte: [
                  "$price",
                  price * 0.25
                ]
              },
              {
                $lte: [
                  "$price",
                  price * 1.75
                ]
              }
            ]
          }
        }
      }
    }
  }
])

Here you first check if field audiPrice is not null then perform the match on that key else on price key.在这里,您首先检查字段 audiPrice 是否不是 null 然后在该键上执行匹配,否则在价格键上执行匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM