Match multiple conditions in an aggregate under expressions

Viewed 1798

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

2 Answers

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] }
      ]
    }
  }
};

Try this:

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