Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - find all search string words in multiple fields

I'm trying to find all words in a search string across multiple fields. For example:

If I were to search "java coffee" in this data:

 { _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 Hut" },
 { _id: 6, name: "Java Coffee", description: "goods Hut" },
 { _id: 7, name: "Coffee Shop", description: "Just coffee Java" }

I would like for it to search for each word individually in each field and return all documents that had each search word in any specified field.

I should get ids 1, 6 and 7 back as results because of these matches:

{ _id: 1, name: "**Java** Hut", description: "**Coffee** and cakes" },<br>
{ _id: 2, name: "Burger Buns", description: "Gourmet hamburgers" },<br>
{ _id: 3, name: "Coffee Shop", description: "Just coffee" },<br>
{ _id: 4, name: "Clothes Clothes Clothes", description: "Discount clothing" },<br>
{ _id: 5, name: "Java Shopping", description: "Indonesian goods Hut" },<br>
{ _id: 6, name: "**Java Coffee**", description: "goods Hut" },<br>
{ _id: 7, name: "Coffee Shop", description: "Just **coffee Java**" }

Any ideas on how I can achieve this in an efficient way for Mongo to execute it?

like image 413
Kendall Avatar asked Nov 02 '25 02:11

Kendall


1 Answers

You can add a text index to your collection to enable text search over multiple fields. In this case:

db.test.createIndex({name: 'text', description: 'text'})

Then, to find docs that contain both "java" and "coffee" in either field, you can execute a text search query with both words quoted to require that both words be found. Quoting the words turn them into phrases which invokes logical AND behavior instead of OR.

db.test.find({$text: {$search: '"java" "coffee"'}})
like image 79
JohnnyHK Avatar answered Nov 04 '25 11:11

JohnnyHK