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

2024-05-14 00:55:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试进行条件查询。我想在整个集合中搜索那些符合25%价格范围的文档,如果文档有特定字段(在本例中为“audiPrice”),我将使用此字段进行搜索,如果此文档没有此字段,我将使用“price”字段

我在mongodb文档(https://docs.mongodb.com/manual/reference/operator/aggregation/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
            }
            }


        }

    }
    }

]

我收到了这个错误信息

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

你知道我怎样才能达到我的目标吗?你知道吗

我正在使用python和pymongo。你知道吗

谢谢


Tags: 文档httpsdocspipelinemongodbmatch价格条件
1条回答
网友
1楼 · 发布于 2024-05-14 00:55:23

可以将$project中的cond或$match stage中的$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
                ]
              }
            ]
          }
        }
      }
    }
  }
])

在这里,您首先检查字段audiPrice是否不为null,然后在该键上执行匹配,否则在price键上执行匹配。你知道吗

相关问题 更多 >