Description
- Laravel-mongodb Version: 3.6.7
- PHP Version: 7.4.9
- Database Driver & Version: php ext mongodb: 1.9.0
Description:
Short: Using where
with a LIKE
on a numeric value in a grouped query causes $where is not allowed in this context
Long: when using where function with a LIKE operator and passing a number as a value together with a groupBy function, mongodb throws exception, because underlying code is using a $where
within a $match
in an aggregation call to Mongo.
so for example Product::query()->where('code', 'LIKE', 12345)->groupBy('name')->get()
will cause MongoDB\Driver\Exception\CommandException : $where is not allowed in this context
and this is confirmed by documentation:
https://docs.mongodb.com/manual/reference/operator/aggregation/match/#restrictions
You cannot use $where in $match queries as part of the aggregation pipeline.
This is caused only when LIKE is being used with numeric value and in conjunction with groupBy (basically with aggregation framework). When Im using LIKE on a string it all works fine (the string needs to be an actual string, not a number in a string type).
Steps to reproduce
- call a query similar to
Product::query()->where('code', 'LIKE', 12345)->groupBy('name')->get()
- see the error
Expected behaviour
I would rather expect the above query to work fine together with a group by. Is there a reason that it's working like this?
Additional info
This is the place in code that generates the $where
which is later used in a $match
https://github.com/jenssegers/laravel-mongodb/blob/master/src/Jenssegers/Mongodb/Query/Builder.php#L1043
Here's how pipeline used in the aggregation call looks like:
{
"$match": {
"$and": [
{
"$where": "\/^^12345$\/.test(this[\"code\"])"
}
]
}
},
{
"$group": {
"_id": {
"name": "$name"
},
"name": {
"$last": "$name"
}
}
}
]