{"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":45807,"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":"6994425a58fa65a0ece5b5f5","content":{"languages":["javascript","typescript"],"difficulty":1},"tags":["javascript","frontend","ui","ux","devtools tech","coding","programming","google","amazon","netflix","ui","ux","interview question"],"slug":"flatten-nested-object-ii---qid---VsqYPIaG0FLFrz8IUWc7","title":"Flatten Nested Object - II","questionId":"VsqYPIaG0FLFrz8IUWc7"},{"_id":"636dfb6fbc012474df4d3802","content":{"languages":["javascript"],"difficulty":1},"tags":["javascript","frontend","coding","devtools tech","interview questions","interview preparation","mcq","programming paradigm","tooling","mdn","js paradigm","programming questions","json","json stringify","json parse"],"slug":"which-function-is-used-to-serialize-an-object-into-a-json-string-in-javascript---qid---Jv5uWoHYYH9sTk0bfnM0","title":"Which function is used to serialize an object into a JSON string in Javascript?","questionId":"Jv5uWoHYYH9sTk0bfnM0"},{"_id":"64624e00d12c1e240201f325","content":{"languages":["javascript","typescript"],"difficulty":2},"tags":["javascript","frontend","coding","devtools tech","ui","ux","egghead","frontend masters","tooling","js questions","frontend interview questions","frontend problems","frontend problem solving"],"slug":"how-to-implement-getelementsbyclassname-or-frontend-problem-solving-or-javascript-interview-question---qid---ZGXls7pg0kEQbcchjNg8","title":"How to implement getElementsByClassName? | Frontend Problem Solving | JavaScript Interview Question","questionId":"ZGXls7pg0kEQbcchjNg8"},{"_id":"6a01a41f8957c8c5cb9e3041","content":{"languages":["javascript","typescript"],"difficulty":1},"tags":["javascript","ui","ux","devtools tech","coding","frontend","interview challenge"],"slug":"chainable-currency-calculator---qid---7YLQzlFTbLwp3MfpQNkH","title":"Chainable Currency Calculator","questionId":"7YLQzlFTbLwp3MfpQNkH"},{"_id":"62f0cd7d77f9961d5b7c3b2e","content":{"languages":["react"],"difficulty":2},"tags":["javascript","frontend coding challenge","reactjs","interview question","lists","machine coding round","ui","frontend engineer","devtools tech","frontend masters","javascript challenges","trello board","trello clone","react trello clone","kanban board","react drag and drop","jira","github","react trello clone board code"],"slug":"trello-board-clone-or-frontend-coding-challenge-or-machine-coding-round---qid---9D6Of9WoD6qWrtGoptSb","title":"Trello Board Clone | Frontend Coding Challenge | Machine Coding Round","questionId":"9D6Of9WoD6qWrtGoptSb"}],"resources":[{"_id":"6a12e1684b3e6d922c549f09","content":{"difficulty":1,"domain":1,"type":1,"isInternal":true,"languages":[]},"tags":["javascript","image","optimisations","ui","ux","devtools tech","tutorial","article","blog","image optimisations"],"slug":"foundations-why-image-optimisation-matters-and-how-browsers-load-images---rid---CLrYWAoK0LTA67R9oV9H","title":"Foundations: Why Image Optimisation Matters & How Browsers Load Images","resourceId":"CLrYWAoK0LTA67R9oV9H"},{"_id":"636cd77320622762d08cfe22","content":{"difficulty":1,"domain":2,"type":1,"isInternal":true},"tags":["javascript","frontend","code","array","interview questions","array polyfills","advanced javascript","js interview questions","hackerrank","codedamn","coding","interview preparation"],"slug":"top-10-javascript-interview-questions-based-on-array-polyfills---rid---oNzRUjONl4YB5ixIEGrl","title":"Top 10 JavaScript Interview Questions based on Array Polyfills","resourceId":"oNzRUjONl4YB5ixIEGrl"},{"_id":"6963e277132ce4e954b04414","content":{"difficulty":4,"domain":2,"type":1,"isInternal":true,"languages":[]},"tags":["javascript","ui","ux","devtools tech","coding","frontend performance","browser rendering cycle"],"slug":"mastering-critical-rendering-path---rid---VyhOczhtA0Ds1kp2s4TN","title":"Mastering Critical Rendering Path","resourceId":"VyhOczhtA0Ds1kp2s4TN"},{"_id":"632544a5ff34d52bbb0796d5","content":{"difficulty":1,"domain":2,"type":2,"isInternal":false},"tags":["javascript","frontend","js","advanced javascript","localstorage","browser","web storage","cookies","session storage","ui","tutorial","youtube"],"slug":"how-to-design-and-implement-localstorage-api-or-frontend-data-structures-or-javascript-interview-questions---rid---kh86UNH6qMxBEaWBcTgr","title":"How to design and implement LocalStorage API | Frontend Data Structures | JavaScript Interview Questions","resourceId":"kh86UNH6qMxBEaWBcTgr"},{"_id":"62d3b928d3473370ac372879","content":{"difficulty":4,"domain":2,"type":2,"isInternal":false},"tags":["javascript","promises","async programming","advanced javascript","interview question","frontend","coding"],"slug":"javascript-promises-fundamentals-every-engineer-should-know-or-part-2-or-event-loop-or-microtasks---rid---oBrzK6Mt7HNAnKBT3ogC","title":"JavaScript Promises Fundamentals Every Engineer Should Know | Part 2 | Event Loop | MicroTasks","resourceId":"oBrzK6Mt7HNAnKBT3ogC"}]}}