View All indexes of the current cluster
> DB. Account. getindexes ()
[
{
" Name " : " _ Id _ " ,
" NS " : " Chatroom. Account " ,
" Key " :{
" _ Id " : 1
},
" V " : 0
}
]
Create a single column Index
> DB. Account. ensureindex ({ " Username " : 1 })
-- 1: ASC-1: DESC
Create a single column unique index
> DB. Account. ensureindex ({ " Username " : 1 },{ " Unique " : True })
Create unique and non-duplicate indexes for a single column
> DB. Account. ensureindex ({ " Username " : 1 },{ " Unique " : True, " Dropdups " : True })
Create a composite index
> DB. Account. ensureindex ({ " Username " : 1 , " Email " : 1 })
> DB. Account. getindexes ()
[
{
" Name " : " _ Id _ " ,
" NS " : " Chatroom. Account " ,
" Key " :{
" _ Id " : 1
},
" V " : 0
},
{
" _ Id " : Objectid ( " 4df7092607444568af61cffd " ),
" NS " : " Chatroom. Account " ,
" Key " :{
" Username " : 1
},
" Name " : " Username_1 " ,
" V " : 0
},
{
" _ Id " : Objectid ( " 4df70dae07444568af61cffe " ),
" NS " : " Chatroom. Account " ,
" Key " :{
" Username " : 1 ,
" Email " : 1
},
" Name " : " Username_1_email_1 " ,
" V " : 0
}
]
Delete Index
> DB. Account. dropindex ({ " Username " : 1 })
{ " Nindexeswas " : 3 , " OK " : 1 }
> DB. Account. dropindex ( " Username_1 " )
{ " Nindexeswas " : 3 , " OK " : 1 }
Delete all clustered Indexes
> DB. Account. dropindexes ()
{
" Nindexeswas " : 3 ,
" MSG " : " Non-_ id indexes dropped for collection " ,
" OK " : 1
}
> DB. Account. getindexes ()
[
{
" Name " : " _ Id _ " ,
" NS " : " Chatroom. Account " ,
" Key " :{
" _ Id " : 1
},
" V " : 0
}
]
-- Deleting all indexes does not delete default indexes.