MongoDB进阶-索引

MongoDB索引管理

Mongodb会自动创建索引_id,且不能被删除

 

普通索引:

db.system.indexes.find()查看索引

 

db.c1.find({name:"user5"}).explain();解析语句

 

>db.c1.find({name:"user5"}).explain()

{

        "cursor" :"BasicCursor",--游标类型,BtreeCursor使用了索引

        "isMultiKey" : false,

        "n" : 1,--返回行数

        "nscannedObjects" : 10,

        "nscanned" : 10,--扫描的行数

        "nscannedObjectsAllPlans" :10,

        "nscannedAllPlans" : 10,

        "scanAndOrder" : false,

        "indexOnly" : false,

        "nYields" : 0,

        "nChunkSkips" : 0,

        "millis" : 0,--耗时

        "server" :"hpo-PC:27017",

        "filterSet" : false

}

字段说明:

cursor:返回游标类型,有BasicCursorBtreeCursor,后者意味着使用了索引。

nscanned:扫描document的行数。

n:返回的文档行数。

millis:耗时(毫秒)。

indexBounds:所用的索引。

 

 

创建索引:

db.c1.ensureIndex({name:1});创建索引;在name字段升序增加索引。(1是升序,-1是降序)

 

db.c1.getIndexKeys();获得索引的key

db.c1.getIndexes();获得索引详细信息

 

    > db.c1.find({name:"user5"}).explain()

{

        "cursor" : "BtreeCursorname_1",--使用了索引

        "isMultiKey" : false,

        "n" : 1,

        "nscannedObjects" : 1,

        "nscanned" : 1,---扫描1

        "nscannedObjectsAllPlans" :1,

        "nscannedAllPlans" : 1,

       "scanAndOrder" : false,

        "indexOnly" : false,

        "nYields" : 0,

        "nChunkSkips" : 0,

        "millis" : 0,

        "indexBounds" : {--使用的索引

                "name" : [

                        [

                                "user5",

                               "user5"

                        ]

                ]

        },

        "server" :"hpo-PC:27017",

        "filterSet" : false

}

 

 

唯一索引:

db.c1.ensureIndex({age:1},{unique:true});给age字段增加升序索引,唯一索引为true;

如果插入重复值会报错: insertDocument:: caused by :: 11000 E11000 duplicate key error index: test.c1.$age_1  dup key: { : 10.0 }

 

 

 

删除索引 :

 db.c1.dropIndex({age:1});--删除c1的age索引.

 

db.c1.dropIndexes();--c1删除所有的索引,_id删不掉。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dingsai88

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值