Docs Menu

Docs HomeMongoid

Text Search

On this page

  • Defining Text Search Index
  • Creating Text Index
  • Querying Using Text Index

MongoDB provides text indexes 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.


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.

Index definition through Mongoid is described in detail on the 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'

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

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

bundle exec rake db:mongoid:create_indexes

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.

←  QueriesAggregation Pipeline →
Share Feedback
© 2023 MongoDB, Inc.


  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2023 MongoDB, Inc.