KingFish
KingFish

Reputation: 9153

Searching with multiple keys and "begins with"

What's the best way to perform the following type of search in a collection named "things":

 mylist = ['lak', 'dodg', 'ang']

and the return could be:

 ["lake", "Lakers", "laky", "dodge", "Dodgers", "Angels", "angle"]

Would I need to perform a separate query for each?

Upvotes: 0

Views: 63

Answers (1)

braza
braza

Reputation: 4672

To do this you want to use the mongodb command $in to search for all things that match with something in your array.

The command you would use would be:

db.things.find( {name: { $in: mylist }} )

But for this to work you want to be using regular expressions in your array, so you can either define them in the array, or if you want to maintain strings then the best thing to do it probably just create another array and loop through and create regex from the strings.

mylist = [/^lak/i, /^dodg/i, /^ang/i]

The ^ making it match only if it begins with the value, and the i at the end to make the search case insensitive.

Upvotes: 1

Related Questions