在表达式下匹配多个聚合条件

6

文件的示例格式:

{
    "_id": {
        "$oid": "5e158e2de6facf7181cc368f"
    },
    "word": "as luck would have it",
}

我正在尝试使用以下表达式来匹配多个条件:

query = {
    "$match": {
        "$expr": {"$eq": [{"$strLenCP": "$word"}, 6],
                  '$lt': [
                      {
                          '$size': {
                              '$split': [
                                  "$word",
                                  " "
                              ]
                          }
                      },
                      2
                  ]
                  }
    }
}

管道的流程如下:

pipeline = [query]
cursor_objects = db['test'].aggregate(pipeline)

在上述查询中,我试图实现单词长度必须为6且不包含任何空格的条件。
但是在这样做时,我遇到了一个错误:
pymongo.errors.OperationFailure: An object representing an expression must have exactly one field: { $eq: [ { $strLenCP: "$word" }, 6 ], $lt: [ { $size: { $split: [ "$word", " " ]

请问如何实现这个功能?

非常感谢任何帮助,TIA(提前致谢)。

2个回答

11
要在 $expr 中使用多个条件,您需要使用 $and 运算符。
query = {
  $match: {
    $expr: {
      $and: [
        {
          $lt: [
            {
              $size: {
                $split: ["$word", " "]
              }
            },
            2
          ]
        },
        { $eq: [{ $strLenCP: "$word" }, 6] }
      ]
    }
  }
};

嘿@Ashh,请问你能帮我解决这个问题吗?https://stackoverflow.com/questions/60810426/how-to-match-a-string-consisting-special-character-like-hyphen-and-spaces/60810505#60810505 - KcH

1

试试这个:

query = {
    "$match": {
        "$expr": {
            $and: [{
                "$eq": [{ "$strLenCP": "$word" }, 6]
            }, {
                '$lt': [{
                        '$size': {
                            '$split': [
                                "$word",
                                " "
                            ]
                        }
                    },
                    2
                ]
            }]
        }
    }
}

谢谢你的帮助伙计@Anuj......抱歉不能接受两个答案!! - KcH
1
@Codenewbie 没问题,伙计。 - Anuj Pancholi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接