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 Query

  先看一下

    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}
 






原文地址:https://www.cnblogs.com/Kellana/p/6636775.html