Based in this example, I'm using $expr
and $regexMatch
to implement "reverse regex" queries in MongoDB. For instance this example works
However, this only seems to work when the regex is in a first level field in the MongoDB document. In the case the regex is within an element in an array (as in this other example I get errors like this:
query failed: (Location51105) Executor error during find command :: caused by :: $regexMatch needs 'regex' to be of type string or regex
Is there any way of supporting this case?
CodePudding user response:
The regex
allows only string input, You can use $map
operator to loop the array elements and check the condition,
$map
to iterate loop ofpatterns.pattern
array and check$regexMatch
condition, it will return boolean value$anyElementTrue
to check if any element is true then it will true
db.collection.find({
"$expr": {
"$anyElementTrue": {
"$map": {
"input": "$patterns.pattern",
"in": {
"$regexMatch": {
"input": "Room1",
"regex": "$$this",
"options": "i"
}
}
}
}
}
})