【MongoDB学习笔记22】MongoDB的索引管理
使用ensureIndex函数创建集合的索引。
对集合而言,每个索引只需要创建一次,重复创建没有任何作用;
> show collections system.indexes users
所有的数据库的索引元数据都存放在system.indexs的集合中;
使用getIndexes函数查看给定的集合上的索引信息:
> db.users.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "blog.users" }, { "v" : 1, "key" : { "username" : 1 }, "name" : "username_1", "ns" : "blog.users" }, { "v" : 1, "key" : { "age" : 1, "username" : 1 }, "name" : "age_1_username_1", "ns" : "blog.users" } ] >
可以适应dropIndex函数删除指定的索引:
> db.users.dropIndex({"username":1}) { "nIndexesWas" : 3, "ok" : 1 } > db.users.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "blog.users" }, { "v" : 1, "key" : { "age" : 1, "username" : 1 }, "name" : "age_1_username_1", "ns" : "blog.users" } ] >
上述的例子中可以看到索引的标识默认格式为keyname1_dir1_keyname2_dir….keynameN_DirN;
也可以指定标识名:
> db.users.ensureIndex({"username":1},{"name":"firstname"}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 2, "numIndexesAfter" : 3, "ok" : 1 } > db.users.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "blog.users" }, { "v" : 1, "key" : { "age" : 1, "username" : 1 }, "name" : "age_1_username_1", "ns" : "blog.users" }, { "v" : 1, "key" : { "username" : 1 }, "name" : "firstname", "ns" : "blog.users" } ] >
修改索引的步骤:删除索引—>创建索引;
删除索引可以直接指定索引标识,例如:
> db.users.dropIndex("firstname") { "nIndexesWas" : 3, "ok" : 1 } > db.users.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "blog.users" }, { "v" : 1, "key" : { "age" : 1, "username" : 1 }, "name" : "age_1_username_1", "ns" : "blog.users" } ] >
本文出自 “缘随心愿” 博客,请务必保留此出处http://281816327.blog.51cto.com/907015/1600882
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。