17

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?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Goalie
  • 3,045
  • 5
  • 35
  • 46

2 Answers2

41

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.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • 1
    Is it possible to do query like `Person.where(first_name: /na/i)` if the field `first_name` is of type `Mongoid::EncryptedString`. I am using mongoid 3.1.6 and getting *TypeError: no implicit conversion of Regexp into String*. – Jagdeep Singh Jan 24 '17 at 08:29
  • @JagdeepSingh, not directly unfortunately. You can iterate through the whole data-set though, something like `Person.all.select { |p| p.first_name ~= /na/i }`, which is obviously less efficient. – TimP Jul 03 '20 at 04:43
7

This is not a "wildcard" search, this is called a regular expression.

/^d/i
  • The two slashes are only the regex delimiters, you search for what is in between those two slashes.
  • The following i is a modifier or option. It changes the matching behaviour of your regex, the i stands for case insensitive, means it matches "d" and "D".
  • The first character ^ is an anchor, it anchors the search pattern to the start of the string, means match "d" only at the start of the string

A good tutorial about regular expressions is the tutorial on regular-expressions.info

If you want to search for a string anywhere in the string, just remove the anchor that binds the pattern to the start, /na/ will find "na" anywhere in the string.

stema
  • 90,351
  • 20
  • 107
  • 135