3

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

Vũ Anh Dũng
  • 980
  • 3
  • 13
  • 32

1 Answers1

2

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.

David
  • 63
  • 4