MongoDB $text search

MongoDB $text search

·

2 min read

  • 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" } )
    
  • Find all documents that contain the word mongo:
    db.collection.find({ $text: { $search: "mongo" } })
    
  • Find all documents that contain the phrasemongo db:
    db.collection.find({ $text: { $search: "\"mongo db\"" } })
    
  • Find all documents that contain the word mongo or database:
    db.collection.find({ $text: { $search: "mongo database" } })
    
  • Find all documents that contain the word mongo and not the word database:
    db.collection.find({ $text: { $search: "mongo -database" } })
    
  • Find all documents that contain the word mongo in the field1 field:
    db.collection.find({ $text: { $search: "mongo", $field: "field1" } })
    

Did you find this article valuable?

Support Inspriom's by becoming a sponsor. Any amount is appreciated!