日期:2014-05-16  浏览次数:20551 次

mongoDB 索引管理

1.单列索引
在字段x上创建索引,1 (ascending) or -1 (descending) 1表示升序(asc),-1表示降序(desc)
> db.data.ensureIndex({x:1})


显示表data里面的所有索引
> db.data.getIndexes()
[
??????? {
??????????????? "name" : "_id_",
??????????????? "ns" : "recommender.data",
??????????????? "key" : {
??????????????????????? "_id" : 1
??????????????? }
??????? },
??????? {
??????????????? "_id" : ObjectId("4befb146b0e29ba1ce20e0bb"),
??????????????? "ns" : "recommender.data",
??????????????? "key" : {
??????????????????????? "x" : 1
??????????????? },
??????????????? "name" : "x_1"
??????? }
]


查找字段x为6的值,此时已经用到索引了
> db.data.find({x:6})
{ "_id" : ObjectId("4bee804ba23d558eb6687117"), "x" : 6, "name" : "caihuafeng1" }


2.默认索引
上述1中db.data.getIndexes()显示出来的一共有2个索引,其中_id是创建表的时候自动创 建的索引,此索引是不能够删除的。

?

3.文档作为索引的键值
a.单列索引
MongoDB的官方文档上面是这样说的:
Documents as Keys


Indexed fields may be of any type, including documents:


往数据库recommender的表data中插入三条记录
> db.data.insert({name:"1616",info:{url:"
http://www.1616.net/",city:"beijing "}});
> db.data.insert({name:"hao123",info:{url:"
http://www.hao123.com/",city:"beijing "}});
> db.data.insert({name:"ll4la",info:{url:"
http://www.114la.com/",city:"dongguan "}});


对字段info创建索引
> db.data.ensureIndex({info: 1});


显示表data上的所有索引
> db.data.getIndexes();
[
??????? {
??????????????? "name" : "_id_",
??????????????? "ns" : "recommender.data",
??????????????? "key" : {
??????????????????????? "_id" : 1
??????????????? }
??????? },
??????? {
??????????????? "_id" : ObjectId("4befb146b0e29ba1ce20e0bb"),
??????????????? "ns" : "recommender.data",
??????????????? "key" : {
??????????????????????? "x" : 1
??????????????? },
??????????????? "name" : "x_1"
??????? },
??????? {
??????????????? "_id" : ObjectId("4befb76bb0e29ba1ce20e0bf"),
??????????????? "ns" : "recommender.data",
??????????????? "key" : {
??????????????????????? "info" : 1
??????????????? },
??????????????? "name" : "info_1"
??????? }
]
查找指定的记录,此时会用到索引
> db.data.find({info: {url:"
http://www.1616.net/",city:"beijing "}});
{ "_id" : ObjectId("4befb711b0e29ba1ce20e0bc"), "name" : "1616", "info" : { "url" : "
http://www.1616.net/ ", "city" : "beijing" } }


b.组合索引
建立组合索引
> db.data.ensureIndex({"info.url":1, "info.city":1});
> db.data.getIndexes();
[
??????? {
??????????????? "name" : "_id_",
??????????????? "ns" : "recommender.data",
??????????????? "key" : {
??????????????????????? "_id" : 1
??????????????? }
??????? },
??????? {
??????????????? "_id" : ObjectId("4befb146b0e29ba1ce20e0bb"),
??????????????? "ns" : "recommender.data",
??????????????? "key" : {
??????????????????????? "x" : 1
??????????????? },
??????????????? "name" : "x_1"
??????? },
??????? {
??????????????? "_id" : ObjectId("4befb76bb0e29ba1ce20e0bf"),
???