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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值