MongoDB(index索引)

作者: 余生筑 | 来源:发表于2017-12-01 15:49 被阅读26次

    时间度小则数据易读,空间度小则数据易写。索引的本质是用空间换取时间,所以创建过多的索引会导致数据易读而难写。

    • 创建按age升序排列的索引
    db.users.createIndex({age:1})
    

    返回结果

    /* 1 */
    {
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1.0
    }
    
    • 查询索引
    db.users.getIndexes()
    

    返回结果

    /* 1 */
    [
        {
            "v" : 2,
            "key" : {
                "_id" : 1
            },
            "name" : "_id_",
            "ns" : "what_i_love.users"
        },
        {
            "v" : 2,
            "unique" : true,
            "key" : {
                "name" : 1
            },
            "name" : "name_1",
            "ns" : "what_i_love.users",
            "background" : true
        }
    ]
    

    上图表示当前数据库一共提供两种索引方式,一种是按_id排序(默认索引),一种是按name排序

    相关文章

      网友评论

        本文标题:MongoDB(index索引)

        本文链接:https://www.haomeiwen.com/subject/hhhbbxtx.html