MongoDB search start of field using regex

Allreadyhome

I have tried a few things to get this working but it always fails. I have a working regex query on a field however want I am trying to achieve is searching on the start of the string. i.e. if you search edi you would get Edinburgh.

I have the following regex query

Locations.find({name : { $regex: location + ".*", $options: 'ix'}}).fetch()

I read about using option m and ^ but it failed to retrieve any results.

RootHacker

To use the regex pattern from your location variable, construct a new RegExp object for e.g this match against all the names starting with location value ,case insensitive match

Locations.find({name : new RegExp('^'+location+'.*', "i")}).fetch()

However case insensitive regex is not index efficient "$regex can only use an index efficiently when the regular expression has an anchor for the beginning (i.e. ^) of a string and is a case sensitive match

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related