使用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" } ] >
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。