How do you do wildcard searches with Mongoid in a Ruby on Rails environment?

Goalie picture Goalie · Mar 30, 2012 · Viewed 14.5k times · Source

The Mongoid documentation only gives one example of doing a wildcard search:

Person.where(first_name: /^d/i)

This finds all people with the first name that starts with "d".

What do the /^ and /i represent?

How do I find all people with their first name having an "na" in the middle of the string? E.g., this query would find "jonathan" since "na" is a substring of the entire string.

Is there website or guide with this information?

Answer

Sergio Tulentsev picture Sergio Tulentsev · Mar 30, 2012

You need this to find people with "na" in the name.

Person.where(first_name: /na/i)

As for your example:

Person.where(first_name: /^d/i)

^ means "beginning of the line". This regex will match all strings where first letter is "d". /i means "do case-insensitive matches". So it'll match both "d" and "D".

Note: only prefix regexes (with ^ in front) are able to use indexes.

Is there website or guide with this information?

Here's my favourite.