Creating and Managing Indexes
DDS uses indexes to improve query efficiency. If there is no index, DDS must scan each document in a collection to select the documents that match the query statement. If a query has an appropriate index, DDS can use the index to limit the number of documents it must examine.
- For details about the rules for creating indexes, see Index.
- For details about the rules of the write/update and delete commands, see Write/Update and Delete.
Indexes
Index |
Description |
---|---|
Default index |
DDS creates a unique index on the _id field during the creation of a collection. A unique index ensures that the indexed fields do not store duplicate values. Do not delete the index from the _id field. In a sharded cluster, if you do not use the _id field as the shard key, your application needs to ensure that the value in the _id field is unique to prevent errors. This is usually done by using the standard automatically generated ObjectId. |
Single field index |
In addition to the _id index defined by DDS, DDS also supports the creation of user-defined ascending/descending indexes on a single field of a document. For single-field indexing and sort operations, the sort order (ascending or descending) of index keys is not important because DDS can traverse the index from any direction. |
Compound indexes |
DDS also supports compound indexes where a single index field contains references to multiple fields. The order of the fields listed in a compound index is important. For example, if there is a compound index {userid: 1, score: -1}, the index is first sorted by userid and then sorted by score within each userid value. The sort order (ascending or descending) of the index keys determines whether the index supports sort operations. |
Multikey index |
DDS uses a multikey index to index the content stored in arrays. If the index contains fields with array values, DDS creates a separate index entry for each element of the array. These multikey indexes allow queries to select documents that contain an array by matching one or more elements of the array. DDS automatically determines whether to create a multi-key index. If the index field contains an array value, you do not need to explicitly specify the multikey type. |
Index Name
The default name for an index is the concatenation of the indexed keys and each key's direction in the index (i.e. 1 or -1) using underscores as a separator. For example, an index created on { item : 1, quantity: -1 } has the name item_1_quantity_-1.
You can create indexes with a custom name, such as one that is more human-readable than the default. For example, consider an application that frequently queries the products collection to populate data on existing inventory. The following createIndex() method creates an index on item and quantity named query for inventory:
db.products.createIndex( { item: 1, quantity: -1 } , { name: "query for inventory" })
You can use the db.collection.getIndexes() method to view the index name. Once an index is created, you cannot rename it. Instead, you must drop and recreate the index with the new name.
DDS provides many different index types to support specific types of data and queries.
Creating an Index
- Run the following command to create an index:
db.collection.createIndex(keys, options)
- key is the index field to be created. The value 1 indicates that the index is created in ascending order, and the value -1 indicates that the index is created in descending order.
- options receives optional parameters. The following table lists common optional parameters.
Parameter
Type
Description
background
Boolean
The default value is false.
The index creation process blocks other database operations. You can specify the background mode to create indexes.
unique
Boolean
The default value is false.
Whether the created index is unique. If this parameter is set to true, a unique index is created.
name
string
Index name. If this parameter is not specified, MongoDB generates an index name by joining the index field name and sorting order.
expireAfterSeconds
integer
TTL value in seconds.
- Create an index.
- Single field index
db.user.createIndex({"name": 1})
The preceding statement creates a single-field index for the name field, which can accelerate various query requests on the name field. This is the most common index type. The ID index created by default is also of this type. {"name": 1} means that indexed items are sorted in ascending order. You can also use {"name": -1} to sort index items in descending order. For a single-field index, the effect of ascending order is the same as that of descending order.
- Composite index
A composite index is an upgraded version of a single sub-index. It creates an index for multiple fields. Documents are sorted by the first field, documents with the same first field are sorted by the second field, and so on.
db.user.createIndex({"name": 1, "age": 1} )
- Multikey index
- If an index field is an array, the created index is called a multikey index.
- A multikey index creates an index for each element of an array.
For example, if a habit field (array) is added to the user collection to describe interests and hobbies, the multikey index of the habit field can be used to query people with the same interests and hobbies.
{"name" : "jack", "age" : 19, habit: ["football, runnning"]} //This is a piece of user information in the person table.
db.user.createIndex( {"habit": 1} ) //Multi-key indexes are automatically created.
db.user.find( {"habit": "football"} ) //Query people with the same interests and hobbies.
- Single field index
- View the collection index.
db.user.getIndexes()
- Deletes all indexes from a collection.
db.user.dropIndexes()
- Deletes a specified index from a collection. Run the following command to delete the name index from the user collection:
db.user.dropIndex({"name": 1})
Precaution
In addition to various types of indexes, DDS allows you to customize some special attributes for indexes.
- Unique index: Ensure that the values of the fields corresponding to an index are different. For example, the _id index is a unique index.
- TTL index: You can specify the expiration time of a document based on a time field. The document expires after the specified time or at a specified time point.
- Partial index: An index is created only for documents that meet a specific condition.
- Sparse index: Indexes are created only for documents that have index fields, which can be considered as a special case of partial indexes.
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot