如果查询程序无法从索引获得排序顺序,就会将结果放在内存中排序,使用排序索引可以提高性能。
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") } } }
默认情况下,在某集合上创建索引,会阻塞该数据库上的所有操作,所以创建索引要养成良好的习惯,采用后台创建索引。
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 } ]