DEV Community

tnguyen303
tnguyen303

Posted on

How to find word in string in mLab and MongoDB

If you are new to programming, you may not know what indexing is. It's actually everywhere around you, if a website has a database, it probably has indexing of some type enabled.

Let me present indexing! Indexing is a process that is run on a database in order to look for things more efficiently, much more efficiently! It does this by looking through all of the database and map the desired fields. Then these new "values/link pairs" are sorted in alphanumeric order. When you hit a keyword, it will go through this ordered list of mapped values and quickly look for your query (Google Big O notation for more details).

Now to the actual code that makes this work:

Example: We want to search for a word in fields "itemName" and "itemDescription" in our MongoDB database. There are other fields defined in our schema but you should not index more than you need as it will create redundant values/links and that would impact your database's query speed. We will use $text notation to look for word(s) in our indexed fields.

First, we have to have a function to run the $text query:

const Inventory = require("./../models/inventory");

const queryResult = function(searchQuery) {
  Inventory.find({ $text: { $search: searchQuery } });
};

console.log(queryResult("shoes"));

Then, we have to our to our mLab/MongoDB database management, requires login (either through Heroku or mLab), select your collection > Indexes tab > Add Index:

alt text

Fill out the desired fields to index, in our case, we are indexing "itemName" and "itemDescription" fields in our database collection; "text" is required to enable the $text notation.

alt text

Finally, hit Create in Background, you will get a popup prompting it may take a few minutes to several hours, depending on the size of your database and number of indexing fields.

That's it! Your site is still operational but until the indexing operation is still going on, you may notice performance issue, so best is to wait.

Thank you for reading my first post, let me know any questions/input/comments!

Top comments (0)