123456789_123456789_123456789_123456789_123456789_

Text Search

MongoDB provides text indexes </core/index-text/> to support text search queries on string content. Text indexes can include any field whose value is a string or an array of string elements.

Note

MongoDB Atlas also provides Atlas Search which is a more powerful and flexible text search solution. The rest of this section discusses text indexes and not Atlas Search.

To perform text search with Mongoid, follow these steps:

  1. Define a text index on a model.
  2. Create the text index on the server.
  3. Build a text search query.

Defining Text Search Index

Index definition through Mongoid is described in detail on the indexes <indexes> page. Text search indexes are described in detail under text indexes in the MongoDB manual. Below is an example definition of a Band model with a text index utilizing the description field:

class Band
  include Mongoid::Document

  field :name, type: String
  field :description, type: String

  index description: 'text'
end

Note that the index type (text) must be given as a string, not as a symbol.

Creating Text Index

To create the index, invoke the db:mongoid:create_indexes Rake task:

bundle exec rake db:mongoid:create_indexes

Querying Using Text Index

To find bands whose description contains "ounces" or its variations, use the \$text operator:

Band.where('$text' => {'$search' => 'ounces'}).to_a
# => [#<Band _id: 5d5341b3ce4ef35d5016746d, name: "foo", description: "ounce">]

Note that the description contains the word "ounce" even though the search query was "ounces".

Note also that when performing text search, the name of the field is not explicitly specified - $text operator searches all fields indexed with the text index.