$regex is reducing the performace in mongodb

31 Views Asked by At

I am trying to query a collection of 7million documents in mongodb by searching a field. I am using regex to perform partial search. It is taking lot of time to give me response. Is there any way we could improve the performance?

I have tried creating text index but $text is supporting partial search as regex

1

There are 1 best solutions below

1
Markus On

Indexes are the main tool to speed up queries against MongoDB. However, when using $regex matches, indexes are only used under some special conditions. This means that the query will end up in a collection scan if you cannot add some additional filter criteria that use an index.

Hence, $text indexes are a much better tool for filtering text content. If this yields too many false positive results, you can use both a $text and a $regex condition to fine-tune the results, e.g.:

db.movies.find({
  $and: [
    {
      $text: {
        $search: "at Tiffany's",
      },
    },
    {
      title: { $regex: /at Tiffany's/ },
    },
  ],
});

This blog post describes the procedure in greater detail.