mongodb索引

 root@test:~# mongo -uroot -p123456 admin
MongoDB shell version: 1.8.1
connecting to: admin
>
> use siyuroom
switched to db siyuroom
> db.favorite.getIndexes()  #取得所有的索引
[
{
"name" : "_id_",
"ns" : "siyuroom.favorite",
"key" : {
"_id" : 1
},
"v" : 0
},
{
"_id" : ObjectId("52845d040e50feaff3991ce7"),
"ns" : "siyuroom.favorite",
"key" : {
"username" : 1
},
"name" : "username_1",
"v" : 0
}
]
>
 
> db.favorite.dropIndex("username_1")#删除索引username_1
{ "nIndexesWas" : 2, "ok" : 1 }
> db.favorite.getIndexes()          
[
{
"name" : "_id_",
"ns" : "siyuroom.favorite",
"key" : {
"_id" : 1
},
"v" : 0
}
]
>
> db.favorite.find({"username":"test"}).explain()#分析删除索引后查询效率
{
"cursor" : "BasicCursor",
"nscanned" : 950225,
"nscannedObjects" : 950225,
"n" : 273,
"millis" : 8292,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
}
}
>
> db.favorite.ensureIndex({"username":1})#添加索引
>
> db.favorite.find({"username":"test"}).explain()#分析添加索引后效率
{
"cursor" : "BtreeCursor username_1",
"nscanned" : 273,
"nscannedObjects" : 273,
"n" : 273,
"millis" : 34,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
"username" : [
[
"test",
"test"
]
]
}
}
>
 
唯一索引
> db.userinfo.insert({"title":"asp"})    
> db.userinfo.insert({"title":"php"})    
> db.userinfo.ensureIndex({"title":1},{"unique":true})#唯一索引
> db.userinfo.insert({"title":"php"})                
E11000 duplicate key error index: siyuroom.userinfo.$title_1  dup key: { : "php" }
 
组合索引
> db.favorite.find({"mobile":"13812345678","username":"test"}).explain();
{
"cursor" : "BtreeCursor username_1",
"nscanned" : 273,
"nscannedObjects" : 273,
"n" : 0,
"millis" : 2,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
"username" : [
[
"test",
"test"
]
]
}
}
> db.favorite.ensureIndex({"mobile":1,"username":1})#组合索引
> db.favorite.getIndexes()                                                  
[
{
"name" : "_id_",
"ns" : "siyuroom.favorite",
"key" : {
"_id" : 1
},
"v" : 0
},
{
"_id" : ObjectId("528774903e015fbbb4e3fc6a"),
"ns" : "siyuroom.favorite",
"key" : {
"username" : 1
},
"name" : "username_1",
"v" : 0
},
{
"_id" : ObjectId("5287793bce036457e10d647e"),
"ns" : "siyuroom.favorite",
"key" : {
"mobile" : 1,
"username" : 1
},
"name" : "mobile_1_username_1",
"v" : 0
}
]
> db.favorite.find({"mobile":"13812345678","username":"test"}).explain();
{
"cursor" : "BtreeCursor mobile_1_username_1",
"nscanned" : 0,
"nscannedObjects" : 0,
"n" : 0,
"millis" : 0,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
"mobile" : [
[
"13812345678",
"13812345678"
]
],
"username" : [
[
"test",
"test"
]
]
}
}

 

    A+
发布日期:2013年12月10日  所属分类:未分类

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: