MongoDB索引
索引的优点:
1、大大减少了服务器需要扫描的数据量;
2、索引可以帮助服务器避免排序或使用临时表;
3、索引可以将随机I/O转换为顺序I/O;
mongodb的索引类型
https://docs.mongodb.com/manual/indexes/#index-types
单字段索引
组合索引(多字段索引)
多键索引
空间索引
文本索引(全文索引)
hash索引
> use testdb
> for (i=1;i<=10000;i++) db.students.insert({name: "student"+i, age: (i%120), address: "#85 Wenhua Road, Zhengzhou, China"})
WriteResult({ "nInserted" : 1 })
> db.students.find().count()
10000
> db.students.find()
创建索引
语法:
> db.mycoll.ensureIndex({KEY: 1})
Key为你要创建的索引字段,1为按升序创建索引,-1为按降序创建索引。
也可以使用多个字段创建索引(关系型数据库中称作复合索引)
> db.mycoll.ensureIndex({"title": 1, "description": -1})
> db.mycoll.help()
> db.students.ensureIndex({name: 1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
查看索引
> db.students.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "testdb.students"
},
{
"v" : 1,
"key" : {
"name" : 1
},
"name" : "name_1",
"ns" : "testdb.students"
}
]
删除指定字段索引
> db.students.dropIndex("name_1")
{ "nIndexesWas" : 2, "ok" : 1 }
> db.students.getIndexes()
创建一个惟一键索引
> db.students.ensureIndex({name: 1}, {unique: true})
> db.students.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "testdb.students"
},
{
"v" : 1,
"unique" : true,
"key" : {
"name" : 1
},
"name" : "name_1",
"ns" : "testdb.students"
}
]
> db.mycoll.dropIndexes() 删除指定collection里的所有索引
> db.mycoll.reIndex() 重建索引
查询分析
> db.students.find({name: "student5000"})
{ "_id" : ObjectId("58bd9ab8661d8c90936418bf"), "name" : "student5000", "age" : 80, "address" : "#85 Wenhua Road, Zhengzhou, China" }
> db.students.find({name: "student5000"}).explain()
{
"cursor" : "BtreeCursor name_1",
"isMultiKey" : false,
"n" : 1,
"nscannedObjects" : 1,
"nscanned" : 1,
"nscannedObjectsAllPlans" : 1,
"nscannedAllPlans" : 1,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 0,
"indexBounds" : {
"name" : [
[
"student5000",
"student5000"
]
]
},
"server" : "aliyun:27017",
"filterSet" : false
}