查看索引情況
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"}]
創(chuàng)建索引
db.imooc_collection.ensureIndex({x:1})
> db.imooc_collection.ensureIndex({x:1}){"createdCollectionAutomatically":false,"numIndexesBefore":1,"numIndexesAfter":2,"ok":1}>
索引可以重復(fù)創(chuàng)建腿椎,對于已經(jīng)創(chuàng)建的索引會直接返回成功
> 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}
創(chuàng)建復(fù)合索引
> db.imooc_2.ensureIndex({x:1,y:1}){"createdCollectionAutomatically":false,"numIndexesBefore":2,"numIndexesAfter":3,"ok":1}
創(chuàng)建過期索引
> db.imooc_2.ensureIndex({time:1},{expireAfterSeconds:30}){"createdCollectionAutomatically":false,"numIndexesBefore":3,"numIndexesAfter":4,"ok":1}