mongoDB 索引

 索引操做

什么是索引

创建文档所在位置的查找清单, 使用索引能够快速查找, 减小遍历次数, 提升查找效率数组

索引约束

即: 什么状况下不适合创建索引?spa

 

  索引自己也占据空间, 数据量很小的时候就不必用索引code

  索引表会根据数据的修改及时变动, 过于频繁的变动也会对数据增删改的效率形成较低blog

  所以大量增删改的时候 查询需求量不大 ,不须要建立索引索引

建立索引

命令文档

db.collection.createIndex()
db.collection.ensureIndex()
db.collection.createIndexes()

功能  建立索引get

参数  索引域 选取要被建立所用的域, 字典形式域名

取值   {域名:1/-1}   1 正向索引, -1  逆向索引io

索引选项class

  一般来加名字, 虽然不设置默认也会自动添加名字 以 域名_1/-1 的形式自动建立

  也能够指定 索引类型 默认是普通索引

  其余类型往下看其余索引部分

ps:

  ensureIndex 和 createIndex 没啥差异,只是名字不同而已.

  ensureIndex 目前也不被官网更新注明, 后期可能会被抹除

  更推荐 createIndex, 更亲和也更被承认

  createIndexes([{},{}]) 建立多个索引, 不必, 索引通常都是建立不多就够了

 实例

  为 name 域 建立正向索引

            > db.class.createIndex({name:1})
            {
                "createdCollectionAutomatically" : false,
                "numIndexesBefore" : 1,
                "numIndexesAfter" : 2,
                "ok" : 1
            }

  经过第二个参数定义索引名称 为 Age 

  为 age 字段 建立正向索引, 且设置名字为 Age

            > db.class.createIndex({age:1},{name:"Age"})
            {
               "createdCollectionAutomatically" : false,
               "numIndexesBefore" : 2,
               "numIndexesAfter" : 3,
               "ok" : 1
            }
            >

查看索引

命令

db.class.getIndexes()

功能  查看索引详细

参数  无参数

返回结果  

  当前集合中的全部索引

  默认 _id 域是由系统自动建立的, 且该索引不能被删除

    1 表示正向索引

    -1 表示逆向索引

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

删除索引

命令

db.collection.dropIndex()

功能  删除一个除了 _id 之外的索引
参数  索引名称 ( 设置的 name ) /  键值对

实例

  > db.class.dropIndex("Age")
  { "nIndexesWas" : 3, "ok" : 1 }

  > db.class.dropIndex({"name":1})
  { "nIndexesWas" : 2, "ok" : 1 }
  >

  删除全部除了 _id 之外的索引

  db.collection.dropIndexes()

其余类型索引

复合索引

根据多个域建立一个索引

 db.class.createIndex({name:1,age:-1},{name:"name_age"})

子文档 / 数组索引

若是某个域建立索引,  该域的值是子文档 / 数组 ,  则对子文档或者数组的某项查询也是索引查询

ps:

  此索引并不须要你专门作什么操做, 只是一种行为定义

  当你给 book :{xx:"xx"} , book 域建立索引

  则 进行 "book.xx" 的查找的时候则为 子文档索引查找

惟一索引

要求建立索引的域不能有重复值

db.class.createIndex({name:1},{unique:true})

稀疏索引

若是建立索引时,某些文档不存在指定索引域,则忽略这些文档

db.class.createIndex({age:1},{sparse:true})
相关文章
相关标签/搜索