{"resource":{"author":{"id":"h2so9H8jPMmgUKGghoNl","name":"Yomesh Gupta","username":"yomeshgupta"},"content":{"link":"https://devtools.tech/speed-up-mongodb-search-queries/","difficulty":2,"domain":3,"type":1,"isInternal":true,"body":"This is blog post is about a problem I faced regarding Search Queries in MongoDB. This is my first blog post so I wanted to start with a simple topic. Feel free to share the feedback.\n\nSo, NoSQL databases are growing in popularity and are used by everyone, from big tech giants to independent developers. NoSQL databases support varied storage approaches such as key-value, document-based and many more. These databases allow developers to store documents that contain various data types. For example, consider a movie database where every document contains a movie `id` and movie `title`.\n\n```js\n{\n  \"id\": 1,\n  \"title\": \"Dawn of Justice\"\n}\n```\n\nTo find the movie with the title `Dawn of Justice`, we can simply run\n\n```js\ndb.movies.find({ title: \"Dawn of Justice\" });\n```\n\nThis command will give us an exact match for the provided string as it will translate to (in SQL terms)\n\n```sql\nselect *\nfrom movies\nwhere title = \"Dawn of Justice\"\n```\n\nHowever, our users would not input search queries like this. They could enter something like `_dawn of justice_, _Dawn of justice_, _DAWN OF JUSTICE_` or any non-exact search query.\n\n![User Search Queries](https://ik.imagekit.io/devtoolstech/speed-up-mongodb-search-queries/user-search-queries-compressed_vZMZL-QYO.gif?ik-sdk-version=javascript-1.4.3&updatedAt=1642921746119)\n\nHere, `_find()_` would not work. In such cases, we can use `Regular Expressions (regex)` which provides a way to match strings against a pattern and MongoDB comes with a built-in regex engine. We can use a query like below where `i` makes the regex case-insensitive.\n\n```js\ndb.movies.find({ title: /Dawn of Justice/i });\n```\n\nWe can leave it to that but as soon as your database size grows, the fetch time of this query will increase and will consume a lot of CPU time.\n\n![Movie Search](https://ik.imagekit.io/devtoolstech/speed-up-mongodb-search-queries/movie-search-min_QtJrK1EdwnW.gif?ik-sdk-version=javascript-1.4.3&updatedAt=1642921745263)\n\nAs you can see in the above demonstration, due to the large size of the database, it takes more than 20 seconds to return the response for a simple search and users will not wait that long. So, what should we do now?\n\n## Text Indexes to the Rescue\n\nStarting from version 2.4, MongoDB supports text indexes to search inside string content. A text index will tokenize and stem the content of the field as in it will break the string into individual words or tokens, and will further reduce them to their stems so that variants of the same word will match. For example, \"talk\" matching \"talks\", \"talked\" and \"talking\" as \"talk\" is a stem of all three. We can create a text index via\n\n```js\ndb.movies.createIndex({ title: \"text\" });\n```\n\nMongoDB provides a `$text` operator which we can use to query data:\n\n```js\ndb.movies.find({ title: { $text: { $search: \"Dawn of Justice\" } });\n```\n\nThis will improve the speed but we will still not get the desired results.\n\n## Power of Text Search with Regular Expressions\n\nWe can use the `$and` operator provided by MongoDB to join Text Search with Regular Expressions. We apply logically `and` to first find a board resultset using Text Search and filter it out using Regular Expressions. If the first condition (text search) fails then regex won't work.\n\nWe can do this by creating a query like\n\n```js\ndb.movies.find({\n  $and: [\n    {\n      $text: {\n        $search: \"Dawn of Justice\",\n      },\n    },\n    {\n      title: {\n        $regex: /Dawn of Justice/i,\n      },\n    },\n  ],\n});\n```\n\nHere, we find a superset of all movies with the title containing the text we are searching for and then filter the resultset with a regex query. If text search yields no result then regex won't execute at all.\n\nThis combination will reduce fetch time and CPU load than using regex queries alone.\n\n![Final Output](https://ik.imagekit.io/devtoolstech/speed-up-mongodb-search-queries/final-output-min_e1nhSB4j4.gif?ik-sdk-version=javascript-1.4.3&updatedAt=1642921744752)\n\nThis is one of the ways to improve your database performance. I learned these optimizations while working on a side project, which is an ML-powered recommendation system. You can check it out here: [re.yomeshgupta.com](https://re.yomeshgupta.com)\n","languages":[],"editorConfig":{}},"stats":{"views":44387,"used":0,"likes":0},"description":"","published":true,"isActive":true,"tags":["node.js","mongodb","backend","database","db","tools","performance","mongo queries"],"slug":"speed-up-mongodb-search-queries---rid---1KlpHxujFKhN2HVJ3AQk","isPremium":false,"categories":[],"requires":[],"_id":"5f1dd537cbec5f7ffc0c2fa8","title":"Speed up MongoDB Search Queries","resourceId":"1KlpHxujFKhN2HVJ3AQk","createdAt":1595790647919,"modifiedAt":1643031137803},"currentUser":null,"isOwner":false,"recommendations":{"questions":[{"_id":"603e31a2a13ae8206b201632","content":{"languages":["javascript","typescript"],"difficulty":2},"tags":["javascript","nodejs","redux","react","interview","advanced js","frontend"],"slug":"how-would-you-implement-createstore-function-from-redux---qid---gDe2UTYeJi0ptBXfuLXL","title":"How would you implement createStore function from Redux?","questionId":"gDe2UTYeJi0ptBXfuLXL"},{"_id":"66eec4af29ee9510ef2e14e5","content":{"languages":["javascript","typescript"],"difficulty":2},"tags":["javascript","frontend","ui","ux","devtools tech","problem solving","adobe","flipkart","paypal","amazon","frontend coding question","interview question"],"slug":"how-to-implement-auto-retry-promise-on-rejection-or-frontend-problem-sovling---qid---dUr6aT6OrbsBxdtA9EQV","title":"How to implement auto-retry Promise on Rejection? | Frontend Problem Sovling","questionId":"dUr6aT6OrbsBxdtA9EQV"},{"_id":"698335e0895fc3bf013c3ff5","content":{"languages":["html"],"difficulty":2},"tags":["javascript","ui","ux","devtools tech","coding","frontend interview","challenges","microsoft interview question"],"slug":"search-page-with-highlighting---qid---J4OIHWaR6t0sOnCyk2ib","title":"Search Page with Highlighting","questionId":"J4OIHWaR6t0sOnCyk2ib"},{"_id":"666d60f6407950304705ec43","content":{"languages":["react"],"difficulty":4},"tags":["javascript","ui","ux","coding","frontend","devtools tech","tutorial","react coding challenge","frontend ui challenge","interview","take home assignment"],"slug":"how-to-build-circles-game-in-react-js-frontend-coding-challenge---qid---Y8acly7B5CmIVAaT5knP","title":"How to build Circles Game in React.js? Frontend Coding Challenge","questionId":"Y8acly7B5CmIVAaT5knP"},{"_id":"6255a79c3ecc8e41a79f0c6a","content":{"languages":["javascript","typescript"],"difficulty":3},"tags":["javascript","classnames","package","polyfills","devtools","frontend","interview questions"],"slug":"implement-classnames-or-javascript-interview-question---qid---3QbZnesP6zJgC2jdLDjf","title":"Implement classNames() | JavaScript Interview Question","questionId":"3QbZnesP6zJgC2jdLDjf"}],"resources":[{"_id":"5f1dd7cbcbec5f7ffc0c2fae","content":{"difficulty":2,"domain":1,"type":1,"isInternal":true},"tags":["node.js","javascript","frontend","frontend fundamentals","js fundamentals","interview questions","backend","backend fundamentals","webpack","inside webpack","advanced webpack","webpack defineplugin","define plugin"],"slug":"optimizing-your-javascript-bundle-or-defineplugin-webpack---rid---kvP5tP0G6isd86ALJUeh","title":"Optimizing your JavaScript Bundle | DefinePlugin Webpack","resourceId":"kvP5tP0G6isd86ALJUeh"},{"_id":"69036a803177c39e85554ace","content":{"difficulty":1,"domain":2,"type":1,"isInternal":true,"languages":[]},"tags":["javascript","frontend","ui","ux","uber","senior frontend engineer"],"slug":"uber-senior-frontend-interview-experience---rid---HhAZPA5jvh67sTfzr8cw","title":"Uber Senior Frontend Interview Experience","resourceId":"HhAZPA5jvh67sTfzr8cw"},{"_id":"6a12f6954b3e6d922c54a4bb","content":{"difficulty":1,"domain":1,"type":1,"isInternal":true,"languages":[]},"tags":["javascript","ui","ux","devtools tech","prioritising critical images","web performance"],"slug":"prioritising-critical-images---rid---BlV5X4YylAW61dYwFmyG","title":"Prioritising Critical Images","resourceId":"BlV5X4YylAW61dYwFmyG"},{"_id":"6206280b1641361c7c65a721","content":{"difficulty":1,"domain":2,"type":1,"isInternal":true},"tags":["","javascript","cookies","remix run","js framework","web fundamentals","frontend","coding","headers","http","redirection","tracking","session"],"slug":"how-to-send-multiple-cookies-in-a-remix-powered-web-app---rid---ndORf220mRIUxvoJPvtb","title":"How to Send Multiple Cookies in a Remix Powered Web App?","resourceId":"ndORf220mRIUxvoJPvtb"},{"_id":"69a7c81b92f33c7d8aa04c9e","content":{"difficulty":1,"domain":1,"type":2,"isInternal":false,"languages":[]},"tags":["javascript","ui","ux","devtools tech","coding","frontend"],"slug":"how-to-refactor-large-codebases---rid---Fyjq9knxMC4wxz0QOfzH","title":"How to refactor large codebases?","resourceId":"Fyjq9knxMC4wxz0QOfzH"}]}}