简体   繁体   中英

Slow regexp query in MongoDB

I have 1.5 million of documents in a collection with an indexed "name" field. Query like db.things.find({name: /^foo/i}) takes about of 5 secs which is very slow. Similar MySQL table with the same records performs SELECT * FROM things WHERE name LIKE 'foo%' in less then 10 ms.

The mongo's explain:

db.things.find({name: /^foo/i}).limit(10).explain()
{
    "cursor" : "BtreeCursor name_1 multi",
    "nscanned" : 325730,
    "nscannedObjects" : 10,
    "n" : 10,
    "millis" : 4758,
    "nYields" : 89,
    "nChunkSkips" : 0,
    "isMultiKey" : false,
    "indexOnly" : false,
    "indexBounds" : {
        "name" : [
            [
                "",
                {

                }
            ],
            [
                /^foo/i,
                /^foo/i
            ]
        ]
    }
}

So is regexp query that slow in mongo or am I doing it wrong?

case insensitive regex search will be slow as it cannot take advantage of the index effectively. If you only use the field for searching, you should consider storing text in all lowercase form and search with case-sensitive regex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM