创建索引
在查询条件的字段或者排序条件的字段上创建索引,可以显著提高执行读效率。但是对于写比读多的,就尽量不要添加索引,因为索引越多,写的操作就会越慢。
- > db.testhint.insertMany([{"a":1,"b":2,"c":3},{"a":2,"b":3,"c":4}])
- ...
- > db.testhint.ensureIndex({"a":1,"b":1})
- ...
- > db.testhint.dropIndex({"a":1,"b":1})
- { "nIndexesWas" : 2, "ok" : 1 }
- # 静默方式创建,其他读写操作仍然可以同步进行,不会产生阻塞。
- > db.testhint.ensureIndex({"a":1,"b":1},{background:true})
- {
- "createdCollectionAutomatically" : false,
- "numIndexesBefore" : 1,
- "numIndexesAfter" : 2,
- "ok" : 1
- }
- # 创建唯一索引
- > db.testhint.ensureIndex({"c":1},{unique:true})
- {
- "createdCollectionAutomatically" : false,
- "numIndexesBefore" : 2,
- "numIndexesAfter" : 3,
- "ok" : 1
- }
- > db.testhint.getIndexes()
- [
- {
- "v" : 2,
- "key" : {
- "_id" : 1
- },
- "name" : "_id_",
- "ns" : "test.testhint"
- },
- {
- "v" : 2,
- "key" : {
- "a" : 1,
- "b" : 1
- },
- "name" : "a_1_b_1",
- "ns" : "test.testhint",
- "background" : true
- },
- {
- "v" : 2,
- "unique" : true,
- "key" : {
- "c" : 1
- },
- "name" : "c_1",
- "ns" : "test.testhint"
- }
- ]
重建索引,在collection大量删除的时候,磁盘空间并不会自动回收,长期这样会产生大量的磁盘碎片,影响磁盘读取性能,所以数据索引需要周期性地重建。
- > db.testhint.reIndex()
- {
- "nIndexesWas" : 3,
- "nIndexes" : 3,
- "indexes" : [
- {
- "v" : 2,
- "key" : {
- "_id" : 1
- },
- "name" : "_id_",
- "ns" : "test.testhint"
- },
- {
- "v" : 2,
- "key" : {
- "a" : 1,
- "b" : 1
- },
- "name" : "a_1_b_1",
- "ns" : "test.testhint",
- "background" : true
- },
- {
- "v" : 2,
- "unique" : true,
- "key" : {
- "c" : 1
- },
- "name" : "c_1",
- "ns" : "test.testhint"
- }
- ],
- "ok" : 1
- }
- # 全库级别的空间回收,可以提高回收的效率
- > db.repairDatabase()
- { "ok" : 1 }
限定返回结果条数
使用limit()函数可以限定返回结果集的记录条数,不仅可以减少数据库服务的资源消耗,还可以减少网络传输的数据量。
- > db.starbucks.find().sort({"_id":-1}).limit(3)
- { "_id" : "9722", "name" : "31st and Sixth Avenue", "street" : "875 Sixth Ave", "city" : "New York", "location" : { "type" : "Point", "coordinates" : [ -73.989251, 40.748026 ] }, "_class" : "example.springdata.mongodb.repo.Store" }
- { "_id" : "9467", "name" : "43rd & Ninth", "street" : "593 Ninth Ave", "city" : "New York", "location" : { "type" : "Point", "coordinates" : [ -73.992514, 40.758934 ] }, "_class" : "example.springdata.mongodb.repo.Store" }
- { "_id" : "9439", "name" : "84th & Third Ave", "street" : "1488 Third Avenue #A", "city" : "New York", "location" : { "type" : "Point", "coordinates" : [ -73.955133, 40.777492 ] }, "_class" : "example.springdata.mongodb.repo.Store" }
只查询用到的字段
只查询使用到的字段,而不是查询所有字段。这样比查询所有字段的效率要高很多。
- > db.starbucks.find({},{"name":1,"city":1}).sort({"_id":-1}).limit(3)
- { "_id" : "9722", "name" : "31st and Sixth Avenue", "city" : "New York" }
- { "_id" : "9467", "name" : "43rd & Ninth", "city" : "New York" }
- { "_id" : "9439", "name" : "84th & Third Ave", "city" : "New York" }
采用Capped Collection
capped集合比普通的集合读写效率要高。因为capped集合是高效率的集合类型。
- > db.createCollection("cappedLogCollection",{capped:true,size:10000,max:3})
- { "ok" : 1 }
- > db.cappedLogCollection.insert({"num":5})
- WriteResult({ "nInserted" : 1 })
- > db.cappedLogCollection.insert({"num":6})
- WriteResult({ "nInserted" : 1 })
- > db.cappedLogCollection.insert({"num":7})
- WriteResult({ "nInserted" : 1 })
- > db.cappedLogCollection.insert({"num":8})
- WriteResult({ "nInserted" : 1 })
- > db.cappedLogCollection.find()
- { "_id" : ObjectId("5c555e82ec962d89c701558a"), "num" : 6 }
- { "_id" : ObjectId("5c555e86ec962d89c701558b"), "num" : 7 }
- { "_id" : ObjectId("5c555e8aec962d89c701558c"), "num" : 8 }
capped集合的特点:
1、capped集合是一种固定大小的集合,使用之前必须先创建它,并且设置其大小。
- size 是整个集合空间大小,单位为【KB】
- max 是集合文档个数上线,单位是【个】
2、capped集合可以插入数据和修改数据,但是不能删除数据,只能使用drop()函数删除整合集合。
3、查询时,没有指定排序,会返回插入时的顺序数据。capped集合可以自动维护插入数据的顺序。
4、当插入的数据超过capped集合的限定大小,数据库会使用FIFO算法,用新数据覆盖最先插入的数据。
采用Server Side Code Execution命令集
Server Side Code Execution是由JavaScript编写,这个过程经过编译和优化后存储在system.js表中。类似存储过程,可以减少网络通信的开销,提高数据库的性能。但是,eval()已经被官方弃用。
- > db.system.js.save({"_id":"echo","value":function(x){return x;}})
- WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
- > db.eval("echo('test')")
- WARNING: db.eval is deprecated
- test
使用hint
MongoDB的查询优化器会自动优化查询,但是有些情况需要强制使用hint才可以提高工作效率,因为hint可以强制要求查询操作使用某个索引。
- indexBounds:使用的索引
- > db.testhint.insertMany([{"a":1,"b":2,"c":3},{"a":2,"b":3,"c":4}])
- {
- "acknowledged" : true,
- "insertedIds" : [
- ObjectId("5c5572468e3fd7101d8d568a"),
- ObjectId("5c5572468e3fd7101d8d568b")
- ]
- }
- > db.testhint.ensureIndex({"a":1,"b":1})
- {
- "createdCollectionAutomatically" : false,
- "numIndexesBefore" : 1,
- "numIndexesAfter" : 2,
- "ok" : 1
- }
- > db.testhint.find({a:1}).explain()
- {
- "queryPlanner" : {
- ...
- },
- "winningPlan" : {
- "stage" : "FETCH",
- "inputStage" : {
- "stage" : "IXSCAN",
- ...
- "indexBounds" : {
- "a" : [
- "[1.0, 1.0]"
- ],
- "b" : [
- "[MinKey, MaxKey]"
- ]
- }
- }
- },
- "rejectedPlans" : [ ]
- },
- "serverInfo" : {
- ...
- },
- "ok" : 1
- }
- > db.testhint.find({a:1}).hint({"a":1,"b":1}).explain()
- {
- "queryPlanner" : {
- ...
- },
- "winningPlan" : {
- "stage" : "FETCH",
- "inputStage" : {
- "stage" : "IXSCAN",
- ...
- "indexBounds" : {
- "a" : [
- "[1.0, 1.0]"
- ],
- "b" : [
- "[MinKey, MaxKey]"
- ]
- }
- }
- },
- "rejectedPlans" : [ ]
- },
- "serverInfo" : {
- ...
- },
- "ok" : 1
- }
新版本MongoDB中,查询优化器已经经过优化,能达到更好的查询效果。是否走索引,可以先用explain()函数检查一下。
采用Profiler
采用Profiler功能会影响效率,使用system.profile来记录,而system.profile是一个Capped集合,所以,对性能影响并不严重。
- # 临时开启,默认记录100ms
- > db.getProfilingLevel()
- 0
- > db.setProfilingLevel(1,100)
- { "was" : 1, "slowms" : 100, "sampleRate" : 1, "ok" : 1 }
- # 查找执行时间大于5ms的profiler日志
- > db.system.profile.find({millis:{$gt:5}})
- # 查看最新产生的profiler记录
- > db.system.profile.find().sort({$natural:-1}).limit(1)