MongoDB索引

创建索引 ensureIndex

 db.scores.ensureIndex({"studentId":1},{"name":"idx_scores_st","background":1});

查看索引 getIndexes

db.scores.getIndexes();

MongoDB索引

删除索引,命令:dropIndex

db.scores.dropIndex({"studentId":1});

查看查询语句解释,命令:explain

db.scores.find({"studentId":"s4"}).explain();

MongoDB索引

唯一索引在创建的时候,指定{“unique”:true}

唯一索引将会保证该字段的数据不会重复,如果重复插入,只会保存一条

索引能保存的数据值必须小于1024字节,这意味着超长的数据,不会保存到索引里,因此也就可以插入多个重复的数据了

唯一索引会把null看作值,所以无法将多个缺少唯一索引的数据插入,这时可以指定sparse来创建一个稀疏索引,如:{“unique”:true,”sparse”:true}