查看當前聚集的全部索引
> db.Account.getIndexes()
[
{
"name" : "_id_",
"ns" : "ChatRoom.Account",
"key" : {
"_id" : 1
},
"v" : 0
}
]
建立單列索引
> db.Account.ensureIndex({"UserName":1})
--1:ASC -1:DESC
建立單列唯一索引
> db.Account.ensureIndex({"UserName" : 1},{"unique" : true})
建立單列唯一不重複索引
> db.Account.ensureIndex({"UserName" : 1},{"unique" : true,"dropDups" : true})
建立複合式索引
> 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
}
]
刪除索引
> db.Account.dropIndex({"UserName":1})
{ "nIndexesWas" : 3, "ok" : 1 }
> db.Account.dropIndex("UserName_1")
{ "nIndexesWas" : 3, "ok" : 1 }
刪除聚集全部的索引
> 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
}
]
--刪除全部索引不會刪除預設索引