MongoDB $text search

Manoj NManoj N
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" } })
    
0
Subscribe to my newsletter

Read articles from Manoj N directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Manoj N
Manoj N

My journey in the tech world started with a passion for software engineering and a curiosity to explore innovative technologies. I've had the opportunity to work with a diverse tech stack, including Node.js, Express, NestJS, Django, Keycloak, Strapi, ReactJS, Sunbird RC (Registry and Credentials), Docker, ONEST and ONDC.