|
| 1 | +--- |
| 2 | +id: mongodb-indexing |
| 3 | +title: MongoDB - Indexing |
| 4 | +sidebar_label: Indexing |
| 5 | +sidebar_position: 18 |
| 6 | +tags: [mongodb, indexing, database, commands] |
| 7 | +description: Learn how to create and manage indexes in MongoDB to improve query performance. |
| 8 | +--- |
| 9 | + |
| 10 | +# MongoDB - Indexing |
| 11 | + |
| 12 | +Indexes support the efficient resolution of queries. Without indexes, MongoDB must scan every document of a collection to select those documents that match the query statement. This scan is highly inefficient and requires MongoDB to process a large volume of data. |
| 13 | + |
| 14 | +Indexes are special data structures that store a small portion of the data set in an easy-to-traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field as specified in the index. |
| 15 | + |
| 16 | +## The createIndex() Method |
| 17 | + |
| 18 | +To create an index, you need to use the `createIndex()` method of MongoDB. |
| 19 | + |
| 20 | +### Syntax |
| 21 | + |
| 22 | +The basic syntax of the `createIndex()` method is as follows: |
| 23 | + |
| 24 | +```shell |
| 25 | +>db.COLLECTION_NAME.createIndex({KEY:1}) |
| 26 | +``` |
| 27 | + |
| 28 | +Here, `KEY` is the name of the field on which you want to create an index, and `1` is for ascending order. To create an index in descending order, you need to use `-1`. |
| 29 | + |
| 30 | +### Example |
| 31 | + |
| 32 | +```shell |
| 33 | +>db.mycol.createIndex({"title":1}) |
| 34 | +{ |
| 35 | + "createdCollectionAutomatically" : false, |
| 36 | + "numIndexesBefore" : 1, |
| 37 | + "numIndexesAfter" : 2, |
| 38 | + "ok" : 1 |
| 39 | +} |
| 40 | +``` |
| 41 | + |
| 42 | +In the `createIndex()` method, you can pass multiple fields to create an index on multiple fields. |
| 43 | + |
| 44 | +```shell |
| 45 | +>db.mycol.createIndex({"title":1,"description":-1}) |
| 46 | +``` |
| 47 | + |
| 48 | +## Index Options |
| 49 | + |
| 50 | +This method also accepts a list of options (which are optional). Following is the list: |
| 51 | + |
| 52 | +| Parameter | Type | Description | |
| 53 | +|---------------------|----------|-----------------------------------------------------------------------------------------------------------------------------------| |
| 54 | +| background | Boolean | Builds the index in the background so that building an index does not block other database activities. Default value is `false`. | |
| 55 | +| unique | Boolean | Creates a unique index so that the collection will not accept insertion of documents where the index key matches an existing value. Specify `true` to create a unique index. Default value is `false`. | |
| 56 | +| name | String | The name of the index. If unspecified, MongoDB generates an index name by concatenating the names of the indexed fields and the sort order. | |
| 57 | +| sparse | Boolean | If `true`, the index only references documents with the specified field. These indexes use less space but behave differently in some situations (particularly sorts). Default value is `false`. | |
| 58 | +| expireAfterSeconds | Integer | Specifies a value, in seconds, as a TTL to control how long MongoDB retains documents in this collection. | |
| 59 | +| weights | Document | The weight is a number ranging from 1 to 99,999 and denotes the significance of the field relative to other indexed fields in terms of the score. | |
| 60 | +| default_language | String | For a text index, the language that determines the list of stop words and the rules for the stemmer and tokenizer. Default value is `English`. | |
| 61 | +| language_override | String | For a text index, specify the name of the field in the document that contains the language to override the default language. Default value is `language`. | |
| 62 | + |
| 63 | +## The dropIndex() Method |
| 64 | + |
| 65 | +You can drop a particular index using the `dropIndex()` method of MongoDB. |
| 66 | + |
| 67 | +### Syntax |
| 68 | + |
| 69 | +The basic syntax of the `dropIndex()` method is as follows: |
| 70 | + |
| 71 | +```shell |
| 72 | +>db.COLLECTION_NAME.dropIndex({KEY:1}) |
| 73 | +``` |
| 74 | + |
| 75 | +Here, `KEY` is the name of the field on which you want to remove an existing index. Instead of the index specification document (above syntax), you can also specify the name of the index directly as: |
| 76 | + |
| 77 | +```shell |
| 78 | +dropIndex("name_of_the_index") |
| 79 | +``` |
| 80 | + |
| 81 | +### Example |
| 82 | + |
| 83 | +```shell |
| 84 | +> db.mycol.dropIndex({"title":1}) |
| 85 | +{ |
| 86 | + "ok" : 0, |
| 87 | + "errmsg" : "can't find index with key: { title: 1.0 }", |
| 88 | + "code" : 27, |
| 89 | + "codeName" : "IndexNotFound" |
| 90 | +} |
| 91 | +``` |
| 92 | + |
| 93 | +## The dropIndexes() Method |
| 94 | + |
| 95 | +This method deletes multiple (specified) indexes on a collection. |
| 96 | + |
| 97 | +### Syntax |
| 98 | + |
| 99 | +The basic syntax of the `dropIndexes()` method is as follows: |
| 100 | + |
| 101 | +```shell |
| 102 | +>db.COLLECTION_NAME.dropIndexes() |
| 103 | +``` |
| 104 | + |
| 105 | +### Example |
| 106 | + |
| 107 | +Assume we have created 2 indexes in the named `mycol` collection as shown below: |
| 108 | + |
| 109 | +```shell |
| 110 | +> db.mycol.createIndex({"title":1,"description":-1}) |
| 111 | +``` |
| 112 | + |
| 113 | +Following example removes the above-created indexes of `mycol`: |
| 114 | + |
| 115 | +```shell |
| 116 | +>db.mycol.dropIndexes({"title":1,"description":-1}) |
| 117 | +{ "nIndexesWas" : 2, "ok" : 1 } |
| 118 | +``` |
| 119 | +
|
| 120 | +## The getIndexes() Method |
| 121 | +
|
| 122 | +This method returns the description of all the indexes in the collection. |
| 123 | +
|
| 124 | +### Syntax |
| 125 | +
|
| 126 | +Following is the basic syntax of the `getIndexes()` method: |
| 127 | +
|
| 128 | +```shell |
| 129 | +db.COLLECTION_NAME.getIndexes() |
| 130 | +``` |
| 131 | +
|
| 132 | +### Example |
| 133 | +
|
| 134 | +Assume we have created 2 indexes in the named `mycol` collection as shown below: |
| 135 | +
|
| 136 | +```shell |
| 137 | +> db.mycol.createIndex({"title":1,"description":-1}) |
| 138 | +``` |
| 139 | +
|
| 140 | +Following example retrieves all the indexes in the collection `mycol`: |
| 141 | +
|
| 142 | +```shell |
| 143 | +> db.mycol.getIndexes() |
| 144 | +[ |
| 145 | + { |
| 146 | + "v" : 2, |
| 147 | + "key" : { |
| 148 | + "_id" : 1 |
| 149 | + }, |
| 150 | + "name" : "_id_", |
| 151 | + "ns" : "test.mycol" |
| 152 | + }, |
| 153 | + { |
| 154 | + "v" : 2, |
| 155 | + "key" : { |
| 156 | + "title" : 1, |
| 157 | + "description" : -1 |
| 158 | + }, |
| 159 | + "name" : "title_1_description_-1", |
| 160 | + "ns" : "test.mycol" |
| 161 | + } |
| 162 | +] |
| 163 | +``` |
| 164 | +
|
| 165 | +## Diagram |
| 166 | +
|
| 167 | +```mermaid |
| 168 | +graph TD; |
| 169 | + A["Start"] --> B["Specify Collection"] |
| 170 | + B --> C{"Create Index"} |
| 171 | + C -->|Single Field| D["createIndex({KEY:1})"] |
| 172 | + C -->|Multiple Fields| E["createIndex({KEY1:1, KEY2:-1})"] |
| 173 | + D --> F["Index Created"] |
| 174 | + E --> F["Index Created"] |
| 175 | + F --> G["Use Index in Queries"] |
| 176 | + G --> H["End"] |
| 177 | +``` |
| 178 | +
|
| 179 | +## Note |
| 180 | +> Indexes can greatly improve query performance, but they also come with overhead. It's important to balance the benefits of indexing with the cost of maintaining them, especially for write-heavy operations. |
0 commit comments