-1

Consider the following piece of code:

Transactions: [
               {name: 123, content: "Starbucks Coffee"},
               {name: 456, content: "Peets Coffee"},
               {name: 789, content: "Amazon gift card"},
               {name: 646, content: "amazon gift card"},
               {name: 779, content: "Acme Corp deposit cheque"},
               {name: 606, content: "acme corp deposit cheque"},
               {name: 879, content: "Dunkin-Donuts"},
               {name: 656, content: "Dunkin Donuts"}
              ];

I need to write a MongoDB framework which does the following:

case 1.)

Input: "Acme Corp" or "acme Corp" or "Acme corp" or "acme corp"

Expected Output:

       [
        {name: 779, content: "Acme Corp deposit cheque"},
        {name: 606, content: "acme corp deposit cheque"}
       ]

case 2.)

Input: "Amazon" or "amazon"

Expected Output:

       [
        {name: 789, content: "Amazon gift card"},
        {name: 646, content: "amazon gift card"}
       ]

case 3.)

Input: "Dunkin" or "dunkin" or "Dunkin-Donuts" or "dunkin-donuts" or "dunkin-Donuts" or "Dunkin-donuts" or "donuts" or "Donuts"

Expected Output:

       [
        {name: 879, content: "Dunkin-Donuts"},
        {name: 656, content: "Dunkin Donuts"}
       ]

Thank you! Any help would be deeply appreciated.

  • Your question title in a Google search [https://www.google.com/search?q=Text+Search+in+MongodDB](https://www.google.com/search?q=Text+Search+in+MongodDB) returns every relevant link you should have read before posting. – Neil Lunn Nov 10 '17 at 02:55

1 Answers1

0

$regex

You can use $regex with the i flag for case-insensitivity:

transactions.find( { content: { $regex: /acme/i } } )

$text

Or use $text (for better performance), by first creating a text index on the field(s) containing the text to be searched

transactions.createIndex( { content: "text" } )

and then:

transactions.find( { $text: { $search: "acme" } } )
Chava Geldzahler
  • 3,605
  • 1
  • 18
  • 32