'Does mongo regex query have character limit, if the regex search string is more than that limit it throws error
I am seeing mongo regex query not returning result when the regex searched string is very big, instead its throwing error. I have a scenario where I append lot of names to do a regex and thus my regex search string goes beyond 40000 characters. eg:
db.getCollection('collection').find(
{"name":{"$regex" :"name1 | name2 | name3", "$options":"-i"}}
)
Solution 1:[1]
Can you explain why you are doing this? The idea of a regex is to create a expression with which you match (multiple) value(s).
example expression:
name\d+
will match on all "namex" vales where x is a decimal.
The idea will be to create a single expression to fullfill your query requirement.
When you want to match on multiple string values you can use $and operator
Solution 2:[2]
Yes, mongoDB regex has character limit, originates from perl regex limit. Because "MongoDB uses Perl compatible regular expressions (i.e. “PCRE” ) version 8.41 with UTF-8 support."MongoDB v3.2
You can see the limitation is 32764 characters:MongoDB add assert of regular expression length
I recently met this issue, and the solution was to use $in query operator instead. $in does not have characters limit. This suits my problem, since it was exact match rather than pattern matching in such long input case.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | HoefMeistert |
Solution 2 | Tanktalus |