In this chapter, we will introduce MongoDB's full-text search, which is different from SQL's "like" operator. MongoDB's full-text search is more efficient for text searching compared to the implementation of "like" in SQL.
Prepare test data
Insert a few records into the stores collection
db.stores.insert(
[
{ _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 text index
To use the ability of full-text search, you need to create a text index. Example:
db.stores.createIndex( { name: "text", description: "text" } )
Explanation:
- Create a text type index for the name and description fields.
Note: A collection only allows one text index, but a text index can include multiple fields.
$text operator
Use the $text operator for text search.
Syntax:
{ $text: { $search: "search keyword" } }
Example:
db.stores.find( { $text: { $search: "java coffee shop" } } )
Explanation:
- Search for documents containing the keywords "coffee", "shop", and "java" in the name and description fields.
Output:
{ "_id" : 3, "name" : "Coffee Shop", "description" : "Just coffee" }
{ "_id" : 1, "name" : "Java Hut", "description" : "Coffee and cakes" }
{ "_id" : 5, "name" : "Java Shopping", "description" : "Indonesian goods" }
Phrase search
db.stores.find( { $text: { $search: "\"coffee shop\"" } } )
Output
{ "_id" : 3, "name" : "Coffee Shop", "description" : "Just coffee" }
Relevance sorting
By default, the results of a $text query are unsorted. The $text query calculates a score (textScore) for the relevance of each document. We can use this score to sort and display documents with higher relevance at the top.
db.stores.find(
{ $text: { $search: "java coffee shop" } },
{ score: { $meta: "textScore" } } // Declare to return the textScore relevance score
).sort( { score: { $meta: "textScore" } } ) // Specify sorting using textScore
Note: MongoDB full-text search does not provide very good support for Chinese phrases.