mongodb 索引的建立

mongodb 建立经常使用的建立索引的有 signle Field Indexes Compound multikey,建立索引就是按照索引字段把documnet 进行排序,索引只存储了document 建立索引的字段的值,建立索引的目的就是为了加快读取数据的速度,固然在插入时建立索引,必然会减慢插入时的速度,mongodb提供了异步的建立索引的方法,能够异步建立,详见这里(http://www.cnblogs.com/Kellana/p/5980410.html)后面咱们进行说明。一个索引的大小少于1024字节,一个单个的collection 中的索引不能超过64个,索引名字的大小不要超过128个字节,Compound 索引中的fields个数不能超过31个,一个multikey不支持coverd Queryhtml

  先看一下mongodb

    signle Field Indexes异步

{
  "_id": ObjectId("570c04a4ad233577f97dc459"), "score": 1034, "location": { state: "NY", city: "New York" } }
 咱们创建一个索引
db.records.createIndex( { score: 1 } ) //注意{score:1}和{score:-1}的区别是score是按照顺序排列,{score:-1}是按照降序排列

能够用索引这样子查询
db.records.find( { score: 2 } ) db.records.find( { score: { $gt: 10 } } )
 Compound Indexes
db.collection.createIndex( { <field1>: <type>, <field2>: <type2>, ... } )
就像上面的这个例子咱们能够这样建立索引
db.records.createIndex( { score: 1 ,"location.state":1})

咱们能够这样查询
db.records.find( { score: 2 ,"location.state":"NY"})

multikey Indexes
在一个
Compound Indexes multikey 中的array 的个数最多只能有一个,不能建立这样的索引以下:
 { _id: 1, a: [ 1, 2 ], b: [ 1, 2 ], category: "AB - both arrays" }
 不能建立这样的 multikey index 
a: 1, b: } 这是错的不能这样建立
{ _id: 1, a: [1, 2], b: 1, category: "A array" } { _id: 2, a: 1, b: [1, 2], category: "B array" }
若是在document 中出现这样的document 那就能够这样建立{a:1,b:1}
相关文章
相关标签/搜索