【问题标题】:Match multiple conditions in an aggregate under expressions在表达式下匹配聚合中的多个条件
【发布时间】:2020-03-17 19:45:16
【问题描述】:

文件格式示例:

{
    "_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

【问题讨论】:

    标签: mongodb aggregation-framework pymongo


    【解决方案1】:

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

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

    【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

    • 感谢@Anuj 的帮助队友.....抱歉不能接受两个答案!
    • @Codenewbie 没问题的芽
    猜你喜欢
    • 1970-01-01
    • 2017-10-16
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 1970-01-01
    相关资源
    最近更新 更多