Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

431
Views
How to create an index for partial text search on MongoDB?

I'm following the tutorial instruction: https://docs.mongodb.com/manual/core/index-text/

This is the sample data:

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" }
   ]
)

Case 1: db.stores.find( { $text: { $search: "java coffee shop" } } ) => FOUND

Case 2: db.stores.find( { $text: { $search: "java" } } ) => FOUND

Case 3: db.stores.find( { $text: { $search: "coff" } } ) => NOT FOUND

I'm expecting case 3 is FOUND because the query is matches a part of java coffee shop

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Case 3 will not work with $text operator and reason is how Mongo Creates Text Indexes.

Mongo takes text indexed fields values and creates separate indexes for each unique word in string and not character(!).

so this means, that in your case for 1 object:

field name will have 2 indexes:

  • java
  • hut

field description will have 3 indexes:

  • coffee
  • and
  • cakes

$text operator compare $search values with this indexes and that's why "coff" will not work.

If you strongly want to take advantages of indexes you have to use $text operator, but it does not give you all flexibility, just like you want.

solution:

You Can simply use $regex with case sensitiveness option (i) and optimize your query with skip and limit.

If you want to return all documents and collection is large, $regex will cause performance issue

you can also check this article https://medium.com/coding-in-depth/full-text-search-part-1-how-to-create-mongodb-full-and-partial-text-search-c09c0bae17a3 and maybe use wildcard indexes for that, but i do not know is it a good practice or not.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!