MongoDB索引创建技巧(一)

2021/4/28 19:30:31

本文主要是介绍MongoDB索引创建技巧(一),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

索引排序

如果查询程序无法从索引获得排序顺序,就会将结果放在内存中排序,使用排序索引可以提高性能。

mongos> use db3
switched to db db3
mongos> db.test.getIndexes()
[
    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "db3.test"
    }
]
mongos> db.test.createIndex({"id":1})
{
    "raw" : {
        "hdshard3/172.16.254.136:40003,172.16.254.137:40003,172.16.254.138:40003" : {
            "createdCollectionAutomatically" : false,
            "numIndexesBefore" : 1,
            "numIndexesAfter" : 2,
            "ok" : 1
        }
    },
    "ok" : 1,
    "operationTime" : Timestamp(1619588710, 6),
    "$clusterTime" : {
        "clusterTime" : Timestamp(1619588710, 6),
        "signature" : {
            "hash" : BinData(0,"ZBt55smIxPY8IGvKiewLnQ1DbEU="),
            "keyId" : NumberLong("6941260985399246879")
        }
    }
}
  • 1表示升序
  • -1表示降序
    无论使用升序还是降序创建索引,查询都可以在任意方向进行排序。
     

后台创建索引

默认情况下,在某集合上创建索引,会阻塞该数据库上的所有操作,所以创建索引要养成良好的习惯,采用后台创建索引。

mongos> db.test.getIndexes()
[
    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "db3.test"
    }
]
mongos> 
mongos> 
mongos> db.test.createIndex({"id":-1},{background:true})
{
    "raw" : {
        "hdshard3/172.16.254.136:40003,172.16.254.137:40003,172.16.254.138:40003" : {
            "createdCollectionAutomatically" : false,
            "numIndexesBefore" : 1,
            "numIndexesAfter" : 2,
            "ok" : 1
        }
    },
    "ok" : 1,
    "operationTime" : Timestamp(1619589015, 1),
    "$clusterTime" : {
        "clusterTime" : Timestamp(1619589015, 1),
        "signature" : {
            "hash" : BinData(0,"1Ka8dn3XtRLJoZbSX4YW0upmPHU="),
            "keyId" : NumberLong("6941260985399246879")
        }
    }
}
mongos> db.test.getIndexes()
[
    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "db3.test"
    },
    {
        "v" : 2,
        "key" : {
            "id" : -1
        },
        "name" : "id_-1",
        "ns" : "db3.test",
        "background" : true
    }
]


这篇关于MongoDB索引创建技巧(一)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程