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

Cod*_*bie 6 mongodb pymongo aggregation-framework

文件样本格式:

{
    "_id": {
        "$oid": "5e158e2de6facf7181cc368f"
    },
    "word": "as luck would have it",
}
Run Code Online (Sandbox Code Playgroud)

我试图匹配表达式中的多个条件,如下所示:

query = {
    "$match": {
        "$expr": {"$eq": [{"$strLenCP": "$word"}, 6],
                  '$lt': [
                      {
                          '$size': {
                              '$split': [
                                  "$word",
                                  " "
                              ]
                          }
                      },
                      2
                  ]
                  }
    }
}
Run Code Online (Sandbox Code Playgroud)

及管道如下:

pipeline = [query]
cursor_objects = db['test'].aggregate(pipeline)
Run Code Online (Sandbox Code Playgroud)

在上面的查询中,我试图实现字长必须为 6 并且不包含任何空格

当我这样做时,我收到错误:

pymongo.errors.OperationFailure: An object representing an expression must have exactly one field: { $eq: [ { $strLenCP: "$word" }, 6 ], $lt: [ { $size: { $split: [ "$word", " " ]
Run Code Online (Sandbox Code Playgroud)

我可以知道我怎样才能实现这一目标吗?

感谢任何帮助,...TIA

Ash*_*shh 11

要使用多个条件,$expr您必须使用$and运算符

query = {
  $match: {
    $expr: {
      $and: [
        {
          $lt: [
            {
              $size: {
                $split: ["$word", " "]
              }
            },
            2
          ]
        },
        { $eq: [{ $strLenCP: "$word" }, 6] }
      ]
    }
  }
};
Run Code Online (Sandbox Code Playgroud)