上线许久的产品忽然爆出了一个Mongodb
查询的BUG,错误以下:css
"exception":"org.springframework.data.mongodb.UncategorizedMongoDbException", "message":"Query failed with error code 96 and error message 'Executor error during find command: OperationFailed: Sort operation used more than the maximum 33554432 bytes of RAM. Add an index, or specify a smaller limit.' on server 127.0.0.1:27017; nested exception is com.mongodb.MongoQueryException: Query failed with error code 96 and error message 'Executor error during find command: OperationFailed: Sort operation used more than the maximum 33554432 bytes of RAM. Add an index, or specify a smaller limit.' on server 127.0.0.1:27017"
缘由比较明确:Sort operation used more than the maximum 33554432 bytes of RAM.
,33554432 bytes
算下来正好是32Mb
,而Mongodb的sort
操做是把数据拿到内存中再进行排序的,为了节约内存,默认给sort
操做限制了最大内存为32Mb
,当数据量愈来愈大直到超过32Mb
的时候就天然抛出异常了!解决方案有两个思路,一个是既然内存不够用那就修改默认配置多分配点内存空间;一个是像错误提示里面说的那样建立索引。
首先说如何修改默认内存配置,在Mongodb
命令行窗口中执行以下命令便可:spring
db.adminCommand({setParameter:1, internalQueryExecMaxBlockingSortBytes:335544320})
我直接把内存扩大了10倍,变成了320Mb。从这里能够看出,除非你服务器的内存足够大,不然sort
占用的内存会成为一个严重的资源消耗!而后是建立索引,也比较简单:mongodb
db.yourCollection.createIndex({<field>:<1 or -1>}) db.yourCollection.getIndexes() //查看当前collection的索引
其中1
表示升序排列,-1
表示降序排列。索引建立以后即时生效,不须要重启数据库和服务器程序,也不须要对原来的数据库查询语句进行修改。建立索引的话也有很差的地方,会致使数据写入变慢,同时Mongodb
数据自己占用的存储空间也会变多。不过从查询性能和服务器资源消耗这两方面来看,经过建立索引来解决这个问题仍是最佳的方案!数据库
来自: https://blog.csdn.net/cloume/article/details/70767061json