Ruby MongoDB Driver documentation

  • Getting Started
    • Installation
    • Driver Compatibility
    • Support
  • Tutorials
    • Quick Start
    • Common Errors
  • Connection & Configuration
    • Creating a Client
    • Authentication
    • Monitoring
    • User Management
  • Working With Data
    • CRUD Operations
    • Bulk Writes
    • Projection
    • Aggregation
    • Map-Reduce
    • Text Search
    • Geospatial Search
    • Query Cache
    • GridFS
    • Change Streams
    • Sessions
    • Transactions
    • Client-Side Encryption
  • Schema Operations
    • Databases
    • Collections
    • Indexing
    • Collations
  • API
  • Release Notes
  • Additional Resources
  • Contribute to the Driver
Theme by the Executable Book Project
  • .txt

Text Search

Text Search#

MongoDB provides :manual:`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 page discusses text indexes and not Atlas Search.

To perform a text search with the Ruby driver, first create a text index with indexes.create_one(). The following command creates a text index on the name field of the restaurants collection in the test database.

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'test')
client['restaurants'].indexes.create_one( { :name => 'text' } )

Once the text index is created you can use it as part of a query. The following code finds all documents in the restaurants collection which contain the word garden, without case sensitivity.

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'test')
client[:restaurants].find(
    { '$text' =>
          { '$search' => 'garden', '$caseSensitive' => false }
    }
      ).each do |document|

    #=> Yields a BSON::Document.

end

previous

Map-Reduce

next

Geospatial Search

© Copyright 2021, MongoDB.