Using Indexes to Increase performance with MongoDB Query
utopian-io·@superoo7·
0.000 HBDUsing Indexes to Increase performance with MongoDB Query
In this tutorial, I will share about better query in Mongo to increase the performance of MongoDB by using Indexes. <center> <br>  <br> [source](https://blog.serverdensity.com/mongodb/) </center> #### What Will I Learn? Write here briefly the details of what the user is going to learn in a bullet list. - Using Indexes to improve mongo query - Basic Find Indexes - Create Indexes - Find available Indexes - Drop Indexes #### Requirements - MongoDB installed (In case you have not, you can check the curriculum at the bottom) - Basic CRUD operation in MongoDB (Check previous post in the curriculum at the bottom) - Basic understanding of Node.js and JavaScript #### Difficulty Advance #### Tutorial Contents In the previous tutorial I talk about CRUD operation with MongoDB. In this tutorial, I will explain how to reduce query time with MongoDB by using Indexes. # What is Indexes? Indexes are like a key to the document. When an index is created, a "key" will be generated; and it point to the document. The reason behind the better performance is that MongoDB will scan less objects , it does not go through other document to search for that object. # Why use Indexes? - Increase in performance - Best practise (Unindexed query will cause performance degradation) - Query is faster when used with some other MongoDB feature like sorting # Basic Indexes Find let say we have a collection name `user` ## Quick comparison between normal find and indexes find Start the data with the following  ### normal find The very straight forward way of query is as follow: `db.users.find({"name.firstName": "Johnson"});` To inspect the query performance, we will be using `.explain()` feature in MongoDB. `db.users.find({"name.firstName": "Johnson"}).explain('executionStats')` The result is in `executionStats.totalDocsExamined`. The total documents examined by MongoDB is 3 documents. ### Indexed find To use Indexed find, we need to use the object Id. `db.users.find({_id: ObjectId('5a8e98444c746d92c494dcd7')}).explain('executionStats');` The result is located same place as the previous one. The total documents examined is reduced to 1. ## Create Index The meaning of create index is to create a documents to index link. This will increase the performance of MongoDB. Based on the data just now, add an age document with `db.users.update({"name.firstName": "Johnson"}, {$set: {"age": 10}})`. ### Before adding Index A quick check in the total doc examined with the following mongo query: `db.users.find({age: 10}).explain('executionStats');` and the total docs examined is 3. ### Added Index Adding index with the following mongo query: `db.users.createIndex({age: 1})`  where `age: 1` means that age is in ascending order and `-1` means descending order. Now, run a quick check in the performance on number of document examined `db.users.find({age: 10}).explain('executionStats');` The result is 1. # Find all available index To check which data is index, simply run `db.users.getIndexes();`  The result is that `_id` and `age` is index. # Drop index Dropping index is also quite straight forward. The command is `db.users.dropIndex({age:1});`  # Final Thoughts MongoDB is a Document based NoSQL, where it provides a lot of powerful ways to structure data. Index is one of the way to increase performance, there is also other approach like arrays, subdocuments and geospatial feature. In the upcoming tutorial, I will cover Data Modelling, Regex and Mapping functions with MongoDB. #### Curriculum - [Getting Started with MongoDB ](https://utopian.io/utopian-io/@superoo7/getting-started-with-mongodb) - [MongoDB: CRUD operation in console and introduction to mongoose.js](https://utopian.io/utopian-io/@superoo7/mongodb-crud-operation-in-console-and-introduction-to-mongoose-js) <br /><hr/><em>Posted on <a href="https://utopian.io/utopian-io/@superoo7/using-indexes-to-increase-performance-with-mongodb-query">Utopian.io - Rewarding Open Source Contributors</a></em><hr/>
👍 superoo7, mitamirandaa, arwinzen, qurator-tier-0, fundurian, feedyourminnows, littlenewthings, legendchew, tatianavishny, gtpjfoodbank, bitrocker2020, kevinwong, arconite, anomadsoul, teammalaysia, vaelriey, zouxx, awesome.ian, dronie, herryazmi11, craftsofluv, teamhumble, iwanderela, kennethtks, joannewong, steemitboard, annabellenoelle, auleo, joeliew, vamos-amigo, davidke20, waterfish0612, iipoh06, yikloongye, yethui, pizzapai, riczlook, johnhooi, r3aperz, hkit98, wilhb81, andrewnoel, watersoo, elvinmas001, yumisee, namchau, ravima27, rose21, legendstick, aidenlee, eliselai, sphenix, piyanka, dashyboy, janicechua, kramuse, babajii, tehtarik, svtan, superoo7-dev, sibehgeng, howtostartablog, branlee87, crypto3d, myach, poeticammo, curie, liberosist, meerkat, locikll, jasimg, hendrikdegrote, coolguy123, anwenbaumeister, rayken04, markangeltrueman, aboutyourbiz, slickhustler007, spectrums, jga, kushed, tensor, ethanlee, wagun001, lenin-mccarthy, elizacheng, velourex, steemedia, teofilex11, dickturpin, bp423, dreamien, redpillproj, steem-id, cebymaster, cotidiana, cryptonator, steemtaker, hrissm, steemulator, aaronleang, nwjordan, utopian-io, williamsblanco, wyp, kilathecla,