上線許久的產品忽然爆出了一個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