Mongodb 索引优化

解释语句

> db.c1.find({name:"user5"}).explain();
{
        "cursor" : "BasicCursor",
        "nscanned" : 19,  扫瞄行数
        "nscannedObjects" : 19,
        "n" : 1,
        "millis" : 92,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "isMultiKey" : false,

        "indexOnly" : false,
        "indexBounds" : {
        }
}

建立普通索引
db.c1.ensureIndex({name:1}); //1,表示升序,0表示降序
> db.c1.getIndexKeys(); //查看集合的索引
[ { “_id” : 1 }, { “name” : 1 } ]

> db.c1.find({name:"user5"}).explain();
{
        "cursor" : "BtreeCursor name_1",
        "nscanned" : 1,
        "nscannedObjects" : 1,
        "n" : 1,
        "millis" : 217,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "isMultiKey" : false,
        "indexOnly" : false,
        "indexBounds" : {
                "name" : [
                        [
                                "user5",
                                "user5"
                        ]
                ]
        }
}
>

加索引之后只查找1行
//唯一索引
db.c1.ensureIndex({age:1},{unique:1});
//查看索引
db.c1.getIndexKeys();
//删除索引 ,除了_id
db.c1.dropIndexes();
//开启慢查询日志

> db.setProfilingLevel(1);
{ "was" : 1, "slowms" : 1000, "ok" : 1 }

0 – 不开启
1- 记录慢命令(默认为>100ms)
2- 记录所有命令
或者再开启服务的时候加上 –slowms=1000 profile=1
/usr/local/mongodb/bin/mongosniff –source net lo //实时查看回环接口mongodb数据动态

发表评论