MongoDB index
Classification of Index
Index Design Principles
index operation
create index
db.collection.createIndex(keys, options)
Parameter |
Type |
Description |
2 |
Boolean |
The index building process will block other database operations, and background can specify to create an index in the background, that is, add the optional parameter . "background" defaults to false. |
unique |
Boolean |
Whether the created 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 |
Version 3.0+ is deprecated . Whether to delete duplicate records when creating a unique index, specify true to create a unique index. The default value is false. |
sparse |
Boolean |
Indexing is not enabled for field data that does not exist in the document; this parameter needs special attention, if it is set to true, documents that do not contain the corresponding field will not be queried in the index field . The default |
expireAfterSeconds |
integer |
Specify a value in seconds to complete the TTL setting and set the lifetime of the collection. |
v |
index version |
The version number of the index The default index version depends on the version mongod was running when creating the index. |
weights |
document |
Index weight value, the value is between 1 and 99,999, indicating the score weight of this index relative to other index fields. |
default_language |
string |
For text indexes , this parameter determines the list of stopwords and rules for stemming and tokenizing . English by default |
language_override |
string |
For text indexes, this parameter specifies the field names contained in the document, the language |
# 创建索引后台执行
db.values.createIndex({open: 1, close: 1}, {background: true})
# 创建唯一索引
db.values.createIndex({title:1},{unique:true})
view index
#查看索引信息
db.books.getIndexes()
#查看索引键
db.books.getIndexKeys()
View index space usage
db.collection.totalIndexSize([is_detail])
delete index
#删除集合指定索引
db.col.dropIndex("索引名称")
#删除集合所有索引 不能删除主键索引
db.col.dropIndexes()
index type
single key index
db.books.createIndex({title:1})
composite index
db.books.createIndex({type:1,favCount:1})
multi-key index
db.inventory.createIndex( { ratings: 1 } )
Notice:
Geospatial Index
db.restaurant.insert({
restaurantId: 0,
restaurantName: "兰州牛肉面",
location: {
type: "Point",
coordinates: [73.97, 40.77]
}
})
Create a 2dsphere index
db.restaurant.createIndex({location : "2dsphere"})
Full text index ( Text Indexes)
MongoDB supports full-text search function, and can realize simple word segmentation search by establishing text index
db.reviews.createIndex( { comments: "text" } )
db.stores.insert([{
_id: 1,
name: "Java Hut",
description: "Coffee and cakes"
},
{
_id: 2,
name: "Burger Buns",
description: "Gourmet hamburgers"
},
{
_id: 3,
name: "Coffee Shop",
description: "Just coffee"
},
{
_id: 4,
name: "Clothes Clothes Clothes",
description: "Discount clothing"
},
{
_id: 5,
name: "Java Shopping",
description: "Indonesian goods"
}])
db.stores.createIndex({name: "text", description: "text"})
db.stores.find({$text: {$search: "java coffee shop"}})
Hash Index (Hashed Indexes)
db.users.createIndex({username : 'hashed'})
Wildcard Indexes
db.products.insert([{
"product_name": "Spy Coat",
"product_attributes": {
"material": ["Tweed", "Wool", "Leather"],
"size": {
"length": 72,
"units": "inches"
}
}
},
{
"product_name": "Spy Pen",
"product_attributes": {
"colors": ["Blue", "Black"],
"secret_feature": {
"name": "laser",
"power": "1000",
"units": "watts",
}
}
},
{
"product_name": "Spy Book"
}])
db.products.createIndex( { "product_attributes.$**" : 1 } )
Wildcard indexes can support any single-field query product_attributes or its embedded fields
db.products.find( { "product_attributes.size.length" : { $gt : 60 } } )
db.products.find( { "product_attributes.material" : "Leather" } )
db.products.find( { "product_attributes.secret_feature.name" : "laser" })
Considerations: Wildcard indexes are not compatible with index types or properties
#通配符索引不能支持以下查询
db.products.find({
"product_attributes": {
$exists: false
}
})
db.products.aggregate([{
$match: {
"product_attributes": {
$exists: false
}
}
}])
#通配符索引不能支持以下查询:
db.products.find({ "product_attributes.colors" : [ "Blue", "Black" ] } )
db.products.aggregate([{
$match : { "product_attributes.colors" : [ "Blue", "Black" ] }
}])
index attribute
Unique Indexes
Partial Indexes
db.restaurants.createIndex(
{ cuisine: 1, name: 1 },
{ partialFilterExpression: { rating: { $gt: 5 } } }
)
# 符合条件,使用索引
db.restaurants.find( { cuisine: "Italian", rating: { $gte: 8 } } )
# 不符合条件,不能使用索引
db.restaurants.find( { cuisine: "Italian" } )
Sparse Indexes
#不索引不包含xmpp_id字段的文档
db.addresses.createIndex( { "xmpp_id": 1 }, { sparse: true } )
TTL Indexes
db.log_events.insertOne( {
"createdAt": new Date(),
"logEvent": 2,
"logMessage": "Success!"
} )
db.log_events.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 20 })
Finally, it was cleaned up, and no data was queried
Index Usage Recommendations
1. Build appropriate indexes for each query
2. Create proper compound indexes and don't rely on cross indexes
3. Composite index field order: Matching conditions first, range conditions after ( Equality First, Range After)
4. Use Covered Index as much as possible
5. Indexing should run in the background
6. Avoid designing too long array index
explain Detailed execution plan
db.collection.find().explain(<verbose>)
schema name |
describe |
queryPlanner _ |
Details of the execution plan, including query plan, collection information, query conditions, best execution plan , query mode, and MongoDB service information, etc. |
exectionStats |
Information such as the execution status of the best |
allPlansExecution |
Select and execute the best execution plan, and return the execution |
# 未创建title的索引
db.books.find({title:"book‐1"}).explain("queryPlanner")
field name |
describe |
plannerVersion |
Execution plan version |
namespace |
collection of queries |
in ndexFilterSet |
whether to use index |
parsedQuery |
query condition |
winningPlan |
Best Execution Plan |
stage |
Query method |
filter |
filter condition |
direction |
query order |
rejectedPlans |
rejected execution plan |
serverInfo |
mongodb server information |
executionStats
#创建索引
db.books.createIndex({title:1})
db.books.find({title:"book‐1"}).explain("executionStats")
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.books.find({title:"book‐1"}).explain("executionStats")
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "restaurant.books",
"indexFilterSet" : false,
"parsedQuery" : {
"title" : {
"$eq" : "book‐1"
}
},
"winningPlan" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"title" : 1
},
"indexName" : "title_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"title" : [ ]
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"title" : [
"[\"book‐1\", \"book‐1\"]"
]
}
}
},
"rejectedPlans" : [ ]
},
"executionStats" : {
"executionSuccess" : true,
"nReturned" : 0,
"executionTimeMillis" : 0,
"totalKeysExamined" : 0,
"totalDocsExamined" : 0,
"executionStages" : {
"stage" : "FETCH",
"nReturned" : 0,
"executionTimeMillisEstimate" : 0,
"works" : 1,
"advanced" : 0,
"needTime" : 0,
"needYield" : 0,
"saveState" : 0,
"restoreState" : 0,
"isEOF" : 1,
"docsExamined" : 0,
"alreadyHasObj" : 0,
"inputStage" : {
"stage" : "IXSCAN",
"nReturned" : 0,
"executionTimeMillisEstimate" : 0,
"works" : 1,
"advanced" : 0,
"needTime" : 0,
"needYield" : 0,
"saveState" : 0,
"restoreState" : 0,
"isEOF" : 1,
"keyPattern" : {
"title" : 1
},
"indexName" : "title_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"title" : [ ]
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"title" : [
"[\"book‐1\", \"book‐1\"]"
]
},
"keysExamined" : 0,
"seeks" : 1,
"dupsTested" : 0,
"dupsDropped" : 0
}
}
},
"serverInfo" : {
"host" : "192.168.30.130",
"port" : 27017,
"version" : "4.4.9",
"gitVersion" : "b4048e19814bfebac717cf5a880076aa69aba481"
},
"ok" : 1
}
field name |
describe |
winningPlan.inputStage |
Used to describe the child stage and provide document and index keys for its parent stage |
winningPlan.inputStage.stage |
subquery method |
winningPlan.inputStage.keyPattern |
The scanned index content |
winningPlan . inputStage.indexName |
index name |
winningPlan.inputStage.isMultiKey |
Whether it is Multikey. Will be true if the index is built on the array |
executionStats.executionSuccess |
Whether the execution is successful |
executionStats.nReturned |
the number returned |
executionStats.executionTimeMillis |
The execution time of this statement |
executionStats.executionStages.executionTim eMillisEstimate |
检索文档获取数据的时间 |
executionStats.executionStages.inputStage.ex ecutionTimeMillisEstimate |
扫描获取数据的时间 |
executionStats.totalKeysExamined |
索引扫描次数 |
executionStats.totalDocsExamined |
文档扫描次数 |
executionStats.executionStages.isEOF |
是否到达 steam 结尾, 1 或者 true 代表已到达结 尾 |
executionStats.executionStages.works |
工作单元数 ,一个查询会分解成小的工作单元 |
executionStats.executionStages.advanced |
优先返回的结果数 |
executionStats.executionStages.docsExamine |
文档检查数 |
状态 |
描述 |
COLLSCAN |
全表扫描 |
IXSCAN |
索引扫描 |
FETCH |
根据索引检索指定文档 |
SHARD_MERGE |
将各个分片返回数据进行合并 |
SORT |
在内存中进行了排序 |
LIMIT |
使用limit限制返回数 |
SKIP |
使用skip进行跳过 |
IDHACK |
对_id进行查询 |
SHARDING_FILTER |
通过mongos对分片数据进行查询 |
COUNTSCAN |
count不使用Index进行count时的stage返回 |
COUNT_SCAN |
count使用了Index进行count时的stage返回 |
SUBPLA |
未使用到索引的$or查询的stage返回 |
TEXT |
使用全文索引进行查询时候的stage返回 |
PROJECTION |
限定返回字段时候stage的返回 |