Ensureindex () method
To create an index, you need to use the Ensureindex () method of MongoDB.
Grammar:
The basic syntax for the Ensureindex () method is as follows yiibai.com
>db. Collection_name. Ensureindex({KEY:1
The key here is to create an index in which 1 is the field name in ascending order. To create a descending index, you need to use-1.
Example
>db. MyCol. Ensureindex({"title":1})
In the Ensureindex () method, you can create an index on multiple fields by multiple fields.
>db. MyCol. Ensureindex({"title":1,"description":-1})
The Ensureindex () method can also accept a list of options (optional), with the list given below:
Example: DB. Custmessage.ensureindex ({"Custno": 1},{unique:true})
Parameters |
type |
Description |
Background |
Boolean |
Indexing is established in the background so that indexing does not prevent other database activities. Specifies true to establish in the background. The default value is False. |
Unique |
Boolean |
Create a unique index so that the collection does not accept the Insert index key or the key that matches the existing value stored in the index document. Specifies to create a unique index. The default value is False. |
Name |
String |
The name of the index. If not specified, MongoDB generates an index name for the index field and the sort order concatenation. |
Dropdups |
Boolean |
Create a unique indexed field that may have duplicates. MongoDB index only the first occurrence of a key, all files removed from the collection contain subsequent occurrences of that key. Specifies to create a unique index. The default value is False. |
Sparse |
Boolean |
If true, the reference refers only to the field specified by the document. These indexes use less space, but in some cases, in particular, a variety of different manifestations. The default value is False. |
Expireafterseconds |
Integer |
Specifies a value in seconds for the TTL control for how long the MongoDB document remains in this collection. |
V |
Index version |
The index version number. The default index version depends on the version of MongoDB run when the index is created. |
Weights |
Document |
Weights are numbers from 1 to 99999, representing the meaning of the field, relative to the other index field fractions. |
Default_language |
String |
For text indexing, decide which language to stop the word and stemmers and the list of markup generation rules. The default value is 中文版. |
Language_override |
String |
For text indexes, the specified name is included in the document that overrides the default language in the Language field. The default value is language. |
MongoDB Set index and ID