It seems that is an expected behavior.
According to the mongodb documentation (griffin mine):
For case sensitive regular Expression queries, if an index exists for
the field, then Mongodb Matches the regular Expression Against the
values in the index, which can be Faster than a Collection scan.
Further Optimization can occur if the regular Expression is a "prefix
Expression", which Means that all potential Matches start with the
same string. This Allows Mongodb to Construct a "range" from that
prefix and only match Against those values from the index that Fall
Within that range.
A regular Expression is a "prefix Expression" if it Starts with a
Caret ( ) or a left Anchor ( A), Followed by a string of simple
Symbols. For example, the regex / abc. */ will be Optimized by matching
only Against the values from the index that start with abc.
That is, to /SAOPAULO/
, Mongo will search for almost all the index keys to find the records that match this search, in which it will probably be faster than a search for the entire collection of records (which already makes up for the index creation).
To \SAO\
, Mongo will scan only the range of indices that start with this value. Thus, it will finish faster the query in the index, because it is a smaller value than \SAOPAULO\
(in which it will traverse more parts of the index).
Thus, it is expected that the query for the initial portion of the desired word will be faster than for the entire word.
The query works, but gets slower with
SAOPAULO
compared to theSAO
? This behavior is consistent?– Dherik
@Dherik That’s right. Increasing the slower string Mongo gets. I set a limit of 20 responses per call with . find(20) to get a little faster.
– usuario
Using index for this column?
– Dherik
@Dherik Yes. I am using index in the columns I use. Does it have anything related to the amount of data in my table?
– usuario
Yes. From what I read here, it seems that when searching for a prefix, the search ends up being faster. See this link. It seems to be a case similar to yours.
– Dherik