{"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":42790,"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":"69c6c5807fa48f2af9fefb80","content":{"languages":["html"],"difficulty":1},"tags":["javascript","ui","ux","devtools tech","interview question","atlassian","frontend coding","ui challenges"],"slug":"real-time-comment-feed---qid---gxnubQDhcOkUH6VxaJra","title":"Real-Time Comment Feed","questionId":"gxnubQDhcOkUH6VxaJra"},{"_id":"65100e5bd5ab2876a4c75093","content":{"languages":["react","html"],"difficulty":1},"tags":["javascript","frontend","coding","ui","ux","reactjs","frontend coding challenge","devtools tech","devkode","javascript interview question","frontend interview question","razorpay","codedamn"],"slug":"build-a-faq-page-or-frontend-coding-challenge-or-react-js-or-html-or-css-or-javascript---qid---ayi5oGVQzM4Jkr7cIZnF","title":"Build a FAQ page | Frontend Coding Challenge | React.js | HTML | CSS | JavaScript","questionId":"ayi5oGVQzM4Jkr7cIZnF"},{"_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"},{"_id":"60ce47a8e541233080dcd5c5","content":{"languages":["react"],"difficulty":4},"tags":["javascript","react","react hooks","frontend","javascript fundamentals","interview questions","frontend fundamentals"],"slug":"how-to-build-a-custom-timer-hook-in-react-js-or-usetimer-or-javascript-interview-question---qid---H5KlkIeowa1LrIn1mSN5","title":"How to build a custom timer hook in React.js? | useTimer | JavaScript Interview Question","questionId":"H5KlkIeowa1LrIn1mSN5"},{"_id":"63bd276d22480f26b3ccc7cd","content":{"languages":["javascript","typescript"],"difficulty":2},"tags":["javascript","frontend","array","coding","ui","ux","polyfills","problem solving","array coding questions","frontend problem solving","js","advanced js","codedamn","egghead","leetcode","alogrithms","data structures","javascript framework","devtools tech","frontend interview preparation","interview questions","interview resources","react","blogs","tutorials","youtube","HTML","CSS","programming content","api design","array fill","array reverse","array sort"],"slug":"how-to-implement-array-prototype-sort-javascript-interview-question-or-problem-solving-or-javascript-polyfills---qid---yLpvrgQ3XG7Em2ehJw1o","title":"How to implement Array.prototype.sort? JavaScript Interview Question | Problem Solving | JavaScript Polyfills","questionId":"yLpvrgQ3XG7Em2ehJw1o"}],"resources":[{"_id":"6990b509d080a1c8aefc6156","content":{"difficulty":4,"domain":1,"type":1,"isInternal":true,"languages":[]},"tags":["javascript","ui","ux","jobs","job search","frontend","coding","devtools tech"],"slug":"how-to-improve-job-search-using-google---rid---JNrLxyNeJ4pMMHD6KnOh","title":"How to improve job search using Google","resourceId":"JNrLxyNeJ4pMMHD6KnOh"},{"_id":"5fc723676d3cda64e470c416","content":{"difficulty":4,"domain":1,"type":2},"tags":["youtube","linkedin","career","devtools tech"],"slug":"find-out-top-skills-in-the-market-or-indemand-introduction---rid---6Mq2Ejdw46VxOaRaYzfC","title":"Find Out Top Skills In The Market | InDemand Introduction","resourceId":"6Mq2Ejdw46VxOaRaYzfC"},{"_id":"5fe98d996d3cda64e470c429","content":{"difficulty":4,"domain":2,"type":2},"tags":["javascript","array","interview questions","frontend","nodejs","inheritance","arrow functions"],"slug":"deeply-nested-array-flat-or-frontend-interview-questions---rid---sTyi2N9I1k6kErptXSUi","title":"Deeply Nested Array Flat | Frontend Interview Questions","resourceId":"sTyi2N9I1k6kErptXSUi"},{"_id":"697cfb276cf04a92bb66eba5","content":{"difficulty":4,"domain":1,"type":1,"isInternal":true,"languages":[]},"tags":["javascript","ui","ux","devtools tech","coding interviews","tutorial","guide","documentation","frontend interviews"],"slug":"guide-to-effective-interview-preparation---rid---6CuY8FFJTPvNHD2SuGLK","title":"Guide to Effective Interview Preparation","resourceId":"6CuY8FFJTPvNHD2SuGLK"},{"_id":"5f2c0c39f81d6d48b5c4cd06","content":{"difficulty":1,"domain":2,"type":1},"tags":["frontend","html","css","webpage performance","css3","page load times"],"slug":"content-visibility-the-new-css-property-that-boosts-your-rendering-performance---rid---qB5R8n3HZ3NWdukfs7zu","title":"content-visibility: the new CSS property that boosts your rendering performance","resourceId":"qB5R8n3HZ3NWdukfs7zu"}]}}