MongoDB $text search
- To perform a text search in MongoDB, you can use the
$text
operator in a query. The$text
operator performs a text search on the string content of the fields indexed with a text index. For example, you could use a query like this to search for documents that contain the word "mongo":db.collection.find({ $text: { $search: "mongo" } })
- To perform a text search, you must have a text index on your collection. You can create a text index on one or more fields in your collection like this:
db.collection.createIndex( { field1: "text", field2: "text" } )
Here are some examples of using the $text operator in MongoDB to perform a text search:
- Find all documents that contain the word
mongo
:db.collection.find({ $text: { $search: "mongo" } })
- Find all documents that contain the phrase
mongo db
:db.collection.find({ $text: { $search: "\"mongo db\"" } })
- Find all documents that contain the word
mongo
ordatabase
:db.collection.find({ $text: { $search: "mongo database" } })
- Find all documents that contain the word
mongo
and not the worddatabase
:db.collection.find({ $text: { $search: "mongo -database" } })
- Find all documents that contain the word
mongo
in thefield1
field:db.collection.find({ $text: { $search: "mongo", $field: "field1" } })