Text Search

    MongoDB supports query operations that perform a text search of string content. To perform text search, MongoDB uses atext indexand theoperator.

    NOTE

    Viewsdo not support text search.

    This example demonstrates how to build a text index and use it to find coffee shops, given only text fields.

    Create a collectionstoreswith the following documents:

    To perform text search queries, you must have atextindex on your collection. A collection can only haveonetext search index, but that index can cover multiple fields.

    For example you can run the following in ashell to allow text search over thenameandfields:db

      $textOperator

      Use the$textquery operator to perform text searches on a collection with a.

      $textwill tokenize the search string using whitespace and most punctuation as delimiters, and perform a logicalORof all such tokens in the search string.

      For example, you could use the following query to find all stores containing any terms from the list “coffee”, “shop”, and “java”:

      Exact Phrase

      1. db.stores.find( { $text: { $search: "java \"coffee shop\"" } } )

      Term Exclusion

      To exclude a word, you can prepend a “” character. For example, to find all stores containing “java” or “shop” but not “coffee”, use the following:db

      Sorting

      MongoDB will return its results in unsorted order by default. However, text search queries will compute a relevance score for each document that specifies how well a document matches the query.

      To sort the results in order of relevance score, you must explicitly project thetextScorefield and sort on it:

      1. db.stores.find(
      2. { $text: { $search: "java coffee shop" } },
      3. { score: { $meta: "textScore" } }
      4. ).sort( { score: { $meta: "textScore" } } )

      Text search is also available in the aggregation pipeline.

      MongoDB supports text search for various languages. SeeText Search Languagesfor a list of supported languages.