MongoDB进阶-索引

来源:互联网 发布:婚纱胸贴哪种好用 知乎 编辑:程序博客网 时间:2024/06/05 22:42

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删不掉。

 

0 0
原创粉丝点击