MongoDB 的索引
1、创建索引 和 查看索引
- 创建索引函数:ensureIndex()
- 功能:创建索引
- 参数:提供索引的类型
- db.student.ensureIndex({stu_ID:1}) ,1为正向索引(优先查找时间最近文档),-1位逆向索引
db.student.ensureIndex({stu_ID:1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
db.student.getIndexes()
{
"v" : NumberInt(2),
"key" : {
"_id" : NumberInt(1)
},
"name" : "_id_",
"ns" : "study.student"
},
{
"v" : NumberInt(2),
"key" : {
"stu_ID" : 1
},
"name" : "stu_ID_1",
"ns" : "study.student"
}
db.student.ensureIndex({stu_name:1,stu_ID:1})
{
"v" : NumberInt(2),
"key" : {
"stu_name" : 1,
"stu_ID" : 1
},
"name" : "stu_name_1_stu_ID_1",
"ns" : "study.student"
}
2、删除索引
- 删除索引函数 :dropIndex()
- 功能:删除一个索引
- 参数:要删除的索引名
db.student.dropIndex({stu_ID:1})
db.studeng.dropIndex({_id:1})
db.student.dropIndex({stu_name:1,stu_ID:1})
- 删除所有索引:dropIndexes()
- 功能:删除指定集合中所有索引,_id索引除外
3、索引类型
- 数组索引:如果对某个数组域创建索引,则对数组中的每个值均创建了索引,通过数组中单个值查询也会提高效率
db.student.ensureIndex({stu_hobby:1})
db.student.find({stu_hobby:"篮球"},{_id:0}).explain()
"indexName" : "stu_hobby_1",
- 子文档索引:某个域值为文档,对其子文档创建索引,则提高通过子文档的查找效率
db.py.ensureIndex({"addr.prov":1})
db.py.find({"addr.prov":"安徽"}).explain()
"indexName" : "addr.prov_1",
db.student.ensureIndex({stu_ID:1},{unique:true})
db.student.ensureIndex({stu_age:1},{unique:true})
db.student.insert({stu_ID:"2019023105"})
- 覆盖索引:查找时,只获取索引项的内容,不链接其他文档内容,从索引表得到查询结果,提高效率
db.student.find({stu_name:"杨浩"},{_id:0,stu_name:1})
- 稀疏索引(间隙索引):只针对有指定域的文档创建索引表,没有该域的文档不插入到索引表中
db.student.ensureIndex({stu_age:1},{sparse:true})
db.student.ensureIndex({txt:"text", description:"text"})
{
"v" : NumberInt(2),
"key" : {
"_fts" : "text",
"_ftsx" : NumberInt(1)
},
"name" : "txt_text_description_text",
"ns" : "study.student",
"weights" : {
"description" : NumberInt(1),
"txt" : NumberInt(1)
},
"default_language" : "english",
"language_override" : "language",
"textIndexVersion" : NumberInt(3)
}
db.student.dropIndex("txt_text_description_text")
db.student.find({$text:{$search:"a b"}})
db.student.find({$text:{$search:"\"a b\""}})
db.student.find({$text:{$search:"-a"}})
4、索引约束
- 影响插入和删除数据的效率,当数据发生修改时,索引必须同步更新
- 索引页占一定的存储空间,当数据量较小时,不适合创建索引