MongoDB 提供了多样性的索引支持,索引信息被保存在system.indexes 中,且默认总是为_id创建索引,它的索引使用基本和MysqL 等关系型数据库一样。其实可以这样说说,索引是凌驾于数据存储系统之上的另一层系统,所以各种结构迥异的存储都有相同或相似的索引实现及使用接口并不足为奇。
基础索引
在字段age 上创建索引,1(升序);-1(降序)
- >db.t3.ensureIndex({age:1})
- >db.t3.getIndexes();
- [
- {
- "name":"_id_",
- "ns":"test.t3",
- "key":{
- "_id":1
- },108); list-style:decimal-leading-zero outside; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> "v":0
- "_id":ObjectId("4fb906da0be632163d0839fe"),108); list-style:decimal-leading-zero outside; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> "age":1
- "name":"age_1",108); list-style:decimal-leading-zero outside; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> "v":0
- }
- ]
- >
上例显示出来的一共有2 个索引,其中_id 是创建表的时候自动创建的索引,此索引是不能够删除的。当系统已有大量数据时,创建索引就是个非常耗时的活,我们可以在后台执行,只需指定“backgroud:true”即可。
- >db.t3.ensureIndex({age:1},{backgroud:true})
文档索引
索引可以任何类型的字段,甚至文档
- db.factories.insert({name:"wwl",addr:{city:"Beijing",state:"BJ"}});
//在addr 列上创建索引
- db.factories.ensureIndex({addr:1});
//下面这个查询将会用到我们刚刚建立的索引
- db.factories.find({addr:{city:"Beijing",state:"BJ"}});