mongodb查询与索引优化

索引:mongodb

    查询语句:数据结构

        db.products.find({
            "details.manufacturer": "acme",
            "pricing.sale": {
                $lt: 7500
            }
        })ide

    单键索引
spa

        制造商(manufacturer)和价格(price)索引

        图片.png

    复合索引图片

        制造商(manufacturer)和价格(price)ci

        图片.png

        复合索引的顺序很重要!
文档

索引的存在会使写操做效率稍低一点。因此,只有会被用到的字段才设置索引!
get

mongodb绝大部分索引使用了B树数据结构it

    惟一索引

        db.users.createIndex({"account": 1}, {"unique": true})

        (若是插入相同的account,会报异常。建议在建立数据以前建立好索引,以对数据进行约束)

        若是该数据不重要,能够删除重复的键值文档,用dropDups参数:

        db.users.createIndex({account: 1}, {unique: true, dropDups: true})

    稀疏索引

        索引默认是密集型的。



explain

经过该命令能够弄清楚mongodb是如何执行查询的

db.the_table.find({"age":{"$gte":0}}).explain("executionStats")

    图片.png

    totalKeysExamined显示整个扫描的索引数为0,docsExamined显示扫描整个集合的9个文档


能够用ensureIndex()或createIndex()来建立索引,其中旧版本用ensureIndex()

    图片.png


getIndexes()方法检查索引是否建立成功:

    图片.png

    (集合如今有2个索引:第一个是标准的_id索引;第二个是咱们建立的num索引。索引名分别叫_id_和num_1)

    设置索引后用explain查看会有变化:

        db.numbers.find({num:{"$gt":19995}}).explain("executionStats")

            图片.png

            图片.png

            图片.png

相关文章
相关标签/搜索