Match multiple conditions in an aggregate under expressions

梦想与她 提交于 2020-03-22 12:56:31

问题


sample format of document:

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

I am trying to match multiple conditions in an expression as:

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

And pipe line as follows:

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

In the above query I am trying to achieve word length must be 6 and it doesn't contain any spaces

When I did this I am getting and error :

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

May I know how could I achieve this ?

any help is appreciated ,...TIA


回答1:


To use multiple conditions in $expr you have to use $and operator

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



回答2:


Try this:

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


来源:https://stackoverflow.com/questions/60721090/match-multiple-conditions-in-an-aggregate-under-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!