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?
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"'}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With