关于给mongodb集合中的某些字段添加索引

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012379844/article/details/85159317

    我们知道mongodb是一种文本数据库,它和mysql数据库一样,都存在索引这一概念。给字段添加索引,可以加快数据查询的速度。当然了,在数据量足够大的情况下,加索引和不加索引的差距是很明显的。但是加了索引之后,在保存方面大概是会很浪费时间的。

1、单一索引

    mongodb中使用以下命令来给字段添加索引。现在先简单的介绍一下,项目中用到的两种单一索引、集合索引。首先在mongodb中添加一个users集合:

> for(var i=0;i<100000;i++){ db.users.insert({username:'user'+i}) }
WriteResult({ "nInserted" : 1 })

查看该集合中存在哪些索引:

> db.users.getIndexes()
[
	{
		"v" : 2,
		"key" : {
			"_id" : 1
		},
		"name" : "_id_",
		"ns" : "test.users"
	}
]

我们先来看一下查询user99999需要用多长的时间:我们可以看到"executionTimeMillis" : 50,也就是查询这一条记录,一共需要遍历"totalDocsExamined" : 100200,消耗了50毫秒。

> db.users.find({"username":"user99999"}).explain("executionStats")
{
	"queryPlanner" : {
		"plannerVersion" : 1,
		"namespace" : "test.users",
		"indexFilterSet" : false,
		"parsedQuery" : {
			"username" : {
				"$eq" : "user99999"
			}
		},
		"winningPlan" : {
			"stage" : "COLLSCAN",
			"filter" : {
				"username" : {
					"$eq" : "user99999"
				}
			},
			"direction" : "forward"
		},
		"rejectedPlans" : [ ]
	},
	"executionStats" : {
		"executionSuccess" : true,
		"nReturned" : 1,
		"executionTimeMillis" : 50,
		"totalKeysExamined" : 0,
		"totalDocsExamined" : 100200,
		"executionStages" : {
			"stage" : "COLLSCAN",
			"filter" : {
				"username" : {
					"$eq" : "user99999"
				}
			},
			"nReturned" : 1,
			"executionTimeMillisEstimate" : 46,
			"works" : 100202,
			"advanced" : 1,
			"needTime" : 100200,
			"needYield" : 0,
			"saveState" : 783,
			"restoreState" : 783,
			"isEOF" : 1,
			"invalidates" : 0,
			"direction" : "forward",
			"docsExamined" : 100200
		}
	},
	"serverInfo" : {
		"host" : "guolujiedeMacBook-Pro.local",
		"port" : 27017,
		"version" : "4.0.2",
		"gitVersion" : "fc1573ba18aee42f97a3bb13b67af7d837826b47"
	},
	"ok" : 1
}

我们现在给该集合的username加上索引,现在有两个索引:

> db.users.createIndex({"username":1})
{
	"createdCollectionAutomatically" : false,
	"numIndexesBefore" : 1,
	"numIndexesAfter" : 2,
	"ok" : 1
}
> db.users.getIndexes()
[
	{
		"v" : 2,
		"key" : {
			"_id" : 1
		},
		"name" : "_id_",
		"ns" : "test.users"
	},
	{
		"v" : 2,
		"key" : {
			"username" : 1
		},
		"name" : "username_1",
		"ns" : "test.users"
	}
]

我们再来查询一下加上索引之后需要消耗的时间:竟然只用了2毫秒,只需要查询一条记录。是不是效率提高了很多。

"executionStats" : {
		"executionSuccess" : true,
		"nReturned" : 1,
		"executionTimeMillis" : 2,
		"totalKeysExamined" : 1,
		"totalDocsExamined" : 1,
		"executionStages" : {
			"stage" : "FETCH",
			"nReturned" : 1,
			"executionTimeMillisEstimate" : 0,
			"works" : 2,
			"advanced" : 1,
			"needTime" : 0,
			"needYield" : 0,
			"saveState" : 0,
			"restoreState" : 0,
			"isEOF" : 1,
			"invalidates" : 0,
			"docsExamined" : 1,
			"alreadyHasObj" : 0,
			"inputStage" : {
				"stage" : "IXSCAN",
				"nReturned" : 1,
				"executionTimeMillisEstimate" : 0,
				"works" : 2,
				"advanced" : 1,
				"needTime" : 0,
				"needYield" : 0,
				"saveState" : 0,
				"restoreState" : 0,
				"isEOF" : 1,
				"invalidates" : 0,
				"keyPattern" : {
					"username" : 1
				},
				"indexName" : "username_1",
				"isMultiKey" : false,
				"multiKeyPaths" : {
					"username" : [ ]
				},
				"isUnique" : false,
				"isSparse" : false,
				"isPartial" : false,
				"indexVersion" : 2,
				"direction" : "forward",
				"indexBounds" : {
					"username" : [
						"[\"user99999\", \"user99999\"]"
					]
				},
				"keysExamined" : 1,
				"seeks" : 1,
				"dupsTested" : 0,
				"dupsDropped" : 0,
				"seenInvalidated" : 0
			}
		}
	},

2、联合索引

    联合索引的添加方法如下:

> db.students.createIndex({"stuId":1,"name":1})
{
	"createdCollectionAutomatically" : false,
	"numIndexesBefore" : 1,
	"numIndexesAfter" : 2,
	"ok" : 1
}
> db.students.getIndexes()
[
	{
		"v" : 2,
		"key" : {
			"_id" : 1
		},
		"name" : "_id_",
		"ns" : "test.students"
	},
	{
		"v" : 2,
		"key" : {
			"stuId" : 1,
			"name" : 1
		},
		"name" : "stuId_1_name_1",
		"ns" : "test.students"
	}
]

    删除指定索引的方法如下:

> db.students.dropIndex("stuId_1_name_1")
{ "nIndexesWas" : 2, "ok" : 1 }

    删除所有索引的方法如下:

> db.students.dropIndexes()
{
	"nIndexesWas" : 1,
	"msg" : "non-_id indexes dropped for collection",
	"ok" : 1
}

猜你喜欢

转载自blog.csdn.net/u012379844/article/details/85159317