# MongoDB Performance<br />ch2 MongoDB Indexes ###### tags: `MongoDB University M201` ## Introduction to Indexes :::info ### index 最佳建立順序 精確匹配 > 排序條件 > 範圍匹配 equality before range equality before sorting ::: * Indexes is try to solve ==slow queries== * b-tree data structure * Indexes increase the speed of ==read== but ==decrease write, update and delete performance== ## Single Field Indexes * Simplest indexes in MongoDB * db.<collection>.createIndex({<field>: <direction>}) * Key features * Keys from only one field * Can find a single value for the indexed field * Can find a range of values * Can use dot notation to index field in subdocuments * Can be used to find several distinct values in a single query :::info We should never index on the field that point to sub document, becuase doing so we'd have to query on the entire subdocument. ::: ## Sorting with Indexes #### Method for sorting * In memory * using an index :::info When sorting with a single field index, sort either ascending or descending regardless of the pyhsical ordering of the index keys ::: ## Querying on Compound Indexes * index on two or more fields * There can be **no more than 32 fields** in a compound index ### Index Prefix ## Multikey Indexes * Index on a field that is an array, cuz for each entry in array the server will create a seperate index key. * Multikey indexes can be constructed over arrays that hold both **scalar values** (e.g. strings, numbers) and **nested documents** ## Partial Indexes **only index the documents in a collection that meet a specified filter expression.** By indexing a subset of the documents in a collection, partial indexes have ==lower storage requirements== and ==reduced performance costs== for index creation and maintenance. ```javascript= // partial index example db.restaurants.createIndex( { cuisine: 1, name: 1 }, { partialFilterExpression: { rating: { $gt: 5 } } } ) ``` ## Sparse Indexes Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value ```javascript= db.addresses.createIndex( { "xmpp_id": 1 }, { sparse: true } ) // partial index can cover sparse index db.addresses.createIndex( { "xmpp_id": 1 }, { "xmpp_id": { $exists: true } } ) ``` ## Text Indexes :::warning **A collection can have at most one text index.** ::: * To create text index ```javascript= db.<collection>.createIndex( { <field>: "text" } ) ``` * Query ```javascript= db.<collection>.find({$text: {$search: "<keyword>"}) ``` * Create index keys for each word of string in field * e.g "MongoDB long sleeve T-shirt" * mongodb * long * sleeve * t * shirt * Case insensitive ## Collation Collation allows users to specify language-specific rules for string comparison, such as rules for ==lettercase== and ==accent marks==. ```javascript= { locale: <string>, caseLevel: <boolean>, caseFirst: <string>, strength: <int> numericOrdering: <boolean>, alternate: <string>, maxVariable: <string>, backwards: <boolean> } ```