MongoDB indexes

an introduction
Indexes can usually greatly improve the efficiency of queries. Without indexes, MongoDB must scan each document in the collection and select those records that meet the query conditions when reading data.
The query efficiency of scanning the entire collection is very low, especially when processing a large amount of data, the query can take tens of seconds or even several minutes, which is very fatal to the performance of the website.
An index is a special data structure that is stored in a collection of data that is easy to traverse and read. An index is a structure that sorts the values ​​of one or more columns in a database table
 
Two ensureIndex() methods
MongoDB uses the ensureIndex() method to create indexes.
1. Grammar
The basic syntax of the ensureIndex() method is as follows:
>db.COLLECTION_NAME.ensureIndex({KEY:1})
The Key value in the syntax is the index field you want to create, 1 is to specify the index to be created in ascending order, and -1 can be specified if you want to create the index in descending order.
2. Examples
  1. > db.col.ensureIndex({"title":1})
  2. {
  3. "createdCollectionAutomatically" : false,
  4. "numIndexesBefore" : 1,
  5. "numIndexesAfter" : 2,
  6. "ok" : 1
  7. }
  8. >
In the ensureIndex() method, you can also set up an index with multiple fields (called a compound index in relational databases).
  1. > db.col.ensureIndex({"title":1,"description":-1})
  2. {
  3. "createdCollectionAutomatically" : false,
  4. "numIndexesBefore" : 2,
  5. "numIndexesAfter" : 3,
  6. "ok" : 1
  7. }
3. ensureIndex() accepts optional parameters. The list of optional parameters is as follows
Parameter Type Description
background Boolean The indexing process will block other database operations. Background can be specified to create indexes in the background, that is, add the "background" optional parameter. "background" defaults to false .
unique Boolean Whether the created index is unique. Specify true 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 by concatenating the index's field names and sort order.
dropDups Boolean 在建立唯一索引时是否删除重复记录,指定 true 创建唯一索引。默认值为 false.
sparse Boolean 对文档中不存在的字段数据不启用索引;这个参数需要特别注意,如果设置为true的话,在索引字段中不会查询出不包含对应字段的文档.。默认值为 false.
expireAfterSeconds integer 指定一个以秒为单位的数值,完成 TTL设定,设定集合的生存时间。
v index version 索引的版本号。默认的索引版本取决于mongod创建索引时运行的版本。
weights document 索引权重值,数值在 1 到 99,999 之间,表示该索引相对于其他索引字段的得分权重。
default_language string 对于文本索引,该参数决定了停用词及词干和词器的规则的列表。 默认为英语
language_override string 对于文本索引,该参数指定了包含在文档中的字段名,语言覆盖默认的language,默认值为 language.
4、实例
在后台创建索引:
db.values.ensureIndex({open: 1, close: 1}, {background: true})
通过在创建索引时加background:true 的选项,让创建工作在后台执行。

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327042720&siteId=291194637