I have this regex on mongodb query to match words by prefix:
{sentence: new RegExp(\'^\'+key,\'gi\')}
What would be the right regex pattern
The other answers suggesting the word boundary matching are neat, but will mean that an index isn't used efficiently. If you need fast lookups, you might want to consider adding a field "words" with each of your words broken up, i.e.
{sentence: "This is a dog",
words: ["This", "is", "a", "dog"]}
After putting an index on the words
field, you can go back to using:
{words: new RegExp('^'+key,'gi')}
and a key
of "do" will now match this object and use an index.