MongoDB 的索引

MongoDB 的索引

1、创建索引 和 查看索引
  • 创建索引函数:ensureIndex()
  • 功能:创建索引
  • 参数:提供索引的类型
  • db.student.ensureIndex({stu_ID:1}) ,1为正向索引(优先查找时间最近文档),-1位逆向索引
db.student.ensureIndex({stu_ID:1})   // 创建自定义索引
{
	"createdCollectionAutomatically" : false,  // 不自动更换链接
	"numIndexesBefore" : 1,    		// 创建索引之前已有一个索引(_id域)
	"numIndexesAfter" : 2,    		// 创建索引之后又两个索引 (增加一个stu_ID索引)
	"ok" : 1
}
  • 查看索引函数getIndexes()
db.student.getIndexes()   		// 查看集合的索引
{
	"v" : NumberInt(2),     	// 版本
	"key" : {
		"_id" : NumberInt(1)   	// 根据_id创建的索引
	},
	"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})   // 创建失败,stu_age域中有重复值

db.student.insert({stu_ID:"2019023105"})   // 插入数据报错,stu_ID 为唯一索引,不允许值重复
  • 覆盖索引:查找时,只获取索引项的内容,不链接其他文档内容,从索引表得到查询结果,提高效率
// stu_name 为索引,查找时只显示 stu_name 时,此操作称之为覆盖索引查找
db.student.find({stu_name:"杨浩"},{_id:0,stu_name:1})  
  • 稀疏索引(间隙索引):只针对有指定域的文档创建索引表,没有该域的文档不插入到索引表中
// 有 stu_age 域的文档会在索引表中,没有stu_age域的文档则不再索引表中
db.student.ensureIndex({stu_age:1},{sparse:true})  // 创建稀疏索引   
  • 文本索引:可以快速进行文本检索
db.student.ensureIndex({txt:"text", description:"text"}) // 将txt域创建文本索引,索引名为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"}})  // 搜索不包含 a 的文档
4、索引约束
  • 影响插入和删除数据的效率,当数据发生修改时,索引必须同步更新
  • 索引页占一定的存储空间,当数据量较小时,不适合创建索引
发布了75 篇原创文章 · 获赞 87 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43883022/article/details/89398072