mongoDB索引属性

创建索引时的格式

db.collection.createIndex( <key and index type specification>, <options> )

其中第二个参数便是索引的属性,比较重要的属性有:

  • 名字
  • 唯一性
  • 稀疏性
  • 是否定时删除

1、名字

db.collection.createIndex({x:1,y:1,z:1,m:1},{name:"normal_index"})

MongoDB会自动的创建,规则是key_1 或者 key_-1  1或者-1代表排序方向,一般影响不大,长度一般有限制125字节。为了见名知意我们可以自己来命名。
删除索引:

db.collection.dropIndex("normal_index")

2、唯一性

db.collection.createIndex( <key and index type specification>, { unique: true } )

MongoDB不能在已经有重复值的字段上创建唯一索引,如果某个文档没有索引的字段,索引会存储null值,null值同样不能重复

3、稀疏性

db.addresses.createIndex( { "x": 1 }, { sparse: true } )

该索引不会存储不包含x字段的文档

如果使用稀疏索引会导致查询结果不完整,除非使用hint()明确指定使用索引,否则MongoDB不会使用该索引。比如下列查询不会返回任何结果

db.addresses.find({x:{$exists:false}}).hint("x_1")

 

posted on 2017-05-04 11:08  cbwleft  阅读(143)  评论(0)    收藏  举报