查看索引情况
db.imooc_collection.getIndexes()
> show tables
> db.imooc_collection.getIndexes()[ ]
> db.imooc_collection.insert({x:1})
WriteResult({"nInserted":1})
> db.imooc_collection.find()
{"_id": ObjectId("586df1ba46208ecdd6d08b36"),"x":1}
> db.imooc_collection.getIndexes()
[{"v":2,"key": {"_id":1},"name":"_id_","ns":"imooc.imooc_collection"}]
创建索引
db.imooc_collection.ensureIndex({x:1})
> db.imooc_collection.ensureIndex({x:1}){"createdCollectionAutomatically":false,"numIndexesBefore":1,"numIndexesAfter":2,"ok":1}>
索引可以重复创建,对于已经创建的索引会直接返回成功
> db.imooc_2.getIndexes()
[{"v":2,"key": {"_id":1},"name":"_id_","ns":"imooc.imooc_2"},{"v":2,"key": {"x":1},"name":"x_1","ns":"imooc.imooc_2"}]
> db.imooc_2.ensureIndex({x:1}){"createdCollectionAutomatically":false,"numIndexesBefore":2,"numIndexesAfter":2,"note":"all indexes already exist","ok":1}
> db.imooc_2.find()
{"_id": ObjectId("586df44f46208ecdd6d08b37"),"x":1}
创建复合索引
> db.imooc_2.ensureIndex({x:1,y:1}){"createdCollectionAutomatically":false,"numIndexesBefore":2,"numIndexesAfter":3,"ok":1}
创建过期索引
> db.imooc_2.ensureIndex({time:1},{expireAfterSeconds:30}){"createdCollectionAutomatically":false,"numIndexesBefore":3,"numIndexesAfter":4,"ok":1}