• mongodb----索引查询与建立


    循环插入数据

    for(i=0;i<500000;i++){db.test.insert({name:'liangqicong'+i,age:i})}

    查询有多少条数据

    db.test.count()

    慢查询配置

    db.getProfilingStatus()

    { "was" : 0, "slowms" : 100, "sampleRate" : 1 }  #这里表示超过100毫秒的查询就会记录在mongodb.log这个日志里面

    执行查询语句

    db.test.find({age:9999})

    查看日志,可以看到执行了161毫秒

    2019-02-16T11:59:51.118+0800 I COMMAND  [conn1] command liangqicong.test appName: "MongoDB Shell" command: find { find: "test", filter: { age: 9999.0 }, lsid: { id: UUID("5cd66bb1-dfec-4f6e-860a-b44bc97a2dce") }, $db: "liangqicong" } planSummary: COLLSCAN keysExamined:0 docsExamined:500000 cursorExhausted:1 numYields:3909 nreturned:1 reslen:169 locks:{ Global: { acquireCount: { r: 3910 } }, Database: { acquireCount: { r: 3910 } }, Collection: { acquireCount: { r: 3910 } } } protocol:op_msg 161ms

    查看查询语句的性能

    db.test.find({age:9999}).explain(true)

    其中会有显示

    "executionStats" : {
    "executionSuccess" : true,
    "nReturned" : 1,
    "executionTimeMillis" : 157,
    "totalKeysExamined" : 0,
    "totalDocsExamined" : 500000,               #总共扫描了500000
    "executionStages" : {
    "stage" : "COLLSCAN",                           #这里是表示全表查询
    "filter" : {
    "age" : {
    "$eq" : 9999
    }
    },

    因为是全表查询模式,而且扫描了500000行,因此会很慢。

    查看表里面有什么索引

    > db.test.getIndexes()
    [
    {
    "v" : 2,
    "key" : {
    "_id" : 1
    },
    "name" : "_id_",
    "ns" : "liangqicong.test"
    }
    ]

    为age字段添加索引

    db.test.ensureIndex({age:1})  (升序)

    删除索引

    db.test.dropIndex({age:1})

    如果用正则去搜索数据的话,索引是无效的。

    mongodb建立唯一索引

    db.test.ensureIndex({userid:1},{unique:true})

    这样,userid就一定是唯一的,跟主键差不多。

  • 相关阅读:
    数论 UVA 10943
    数论 UVA 11889
    数论 UVA 11388
    UVA 572
    hdu 1016
    poj 1308
    poj 1363
    java web-----servelet
    java IO文件读写例子(OutputStream,InputStream,Writer,Reader)
    java web环境配置类型问题
  • 原文地址:https://www.cnblogs.com/QicongLiang/p/10387319.html
Copyright © 2020-2023  润新知