Perform a Text Search (Legacy)执行文本搜索(旧版)

MongoDB offers a full-text search solution, MongoDB Atlas Search, for data hosted on MongoDB Atlas. MongoDB为MongoDB Atlas上托管的数据提供了一个全文搜索解决方案,MongoDB阿特拉斯搜索A legacy text search capability is available for users self-managing MongoDB deployments.传统文本搜索功能可用于用户自我管理MongoDB部署。

To run legacy text search queries, you must have a text index on your collection. 若要运行旧版文本搜索查询,必须在集合上创建text索引。MongoDB provides text indexes to support text search queries on string content. MongoDB提供文本索引以支持对字符串内容的文本搜索查询。text indexes can include any field whose value is a string or an array of string elements. text索引可以包括其值为字符串或字符串元素数组的任何字段。A collection can only have one text search index, but that index can cover multiple fields.

See the Text Indexes section for a full reference on text indexes, including behavior, tokenization, and properties.

Examples示例

This example demonstrates how to build a text index and use it to find coffee shops, given only text fields.这个例子演示了如何构建一个文本索引,并使用它来查找咖啡店,只给出文本字段。

Create a Collection创建集合

Create a collection stores with the following documents:使用以下文档创建集合stores

db.stores.insertMany(
   [
     { _id: 1, name: "Java Hut", description: "Coffee and cakes" },
     { _id: 2, name: "Burger Buns", description: "Gourmet hamburgers" },
     { _id: 3, name: "Coffee Shop", description: "Just coffee" },
     { _id: 4, name: "Clothes Clothes Clothes", description: "Discount clothing" },
     { _id: 5, name: "Java Shopping", description: "Indonesian goods" }
   ]
)

Create a Text Index创建文本索引

Run the following in mongosh to allow text search over the name and description fields:

db.stores.createIndex( { name: "text", description: "text" } )

Search for an Exact Phrase

You can also search for exact phrases by wrapping them in double-quotes. If the $search string includes a phrase and individual terms, text search will only match documents that include the phrase.

For example, the following will find all documents containing "coffee shop":

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

For more information, see Phrases.

Exclude a Term

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.stores.find( { $text: { $search: "java shop -coffee" } } )

Sort the Results

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 the $meta textScore field and sort on it:

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

Text search is also available in the aggregation pipeline.

←  Text SearchText Search Operators (Legacy) →