php mongo sort -1出错,mongoDB排序引起的ERROR

mongo 使用过程中遇到了一个问题,需求就是要对mongo 库中数据进行排序查询

logger.info("历史采集汇总");// 一天数据

calendar = Calendar.getInstance();

calendar.add(Calendar.HOUR_OF_DAY, -24);

cond = new BasicDBObject();

cond.put("workTime", new BasicDBObject(QueryOperators.GTE, calendar.getTime()));

feild = new BasicDBObject();

query = new BasicQuery(cond, feild);

query.with(new Sort(Sort.Direction.DESC, "stockId"));

List dayStockList = mongoTemplate.find(query, HashMap.class, "stockAnls");

logger.info("分析数据数量24"+dayStockList.size());

query = new BasicQuery(cond, feild);

query.with(new Sort(Sort.Direction.DESC, "topicId"));

List dayTopicList = mongoTemplate.find(query, HashMap.class, "topicAnls");

logger.info("分析数据数量24"+dayTopicList.size());

这种方法在库里数据容量小的情况下完全可以胜任,但是如果数据过多,这时会报一个 ERROR

2018/06/28-14:40:22 [pool-1-thread-1] ERROR

org.springframework.scheduling.support.TaskUtils$LoggingErrorHandler-

Unexpected error occurred in scheduled task.

org.springframework.data.mongodb.UncategorizedMongoDbException:

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 47.98.85.173:3717; 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 47.98.85.173:3717

按照错误提示,知道这是排序的时候报的错,因为 mongo 的 sort 操作是在内存中操作的,必然会占据内存,同时mongo内的一个机制限制排序时最大内存为 32M,当排序的数据量超过 32M,就会报上面的这个错,解决办法就像上面提示的意思,一是加大 mongo的排序内存,这个一般是运维来管,也有弊端,就是数据量如果再大,还要往上加。

另一个办法就是加索引,这个方法还是挺方便的。创建索引及时生效,不需要重启服务。创建索引:

db.你的collection.createIndex({"你的字段": -1}),此处 -1 代表倒序,1 代表正序;

db.你的collecton.getIndexes();

这两个语句,第一个是添加索引,第二个是查询索引,如果查看到你刚才添加的那个索引字段,就说明索引添加成功了。这时候在你的程序里再运用 sort 方法的话,这样就不会报错而且速度很快。

添加索引会带来一定的弊端,这样会导致数据插入的时候相对之前较慢,因为索引会占据空间的。综上考虑,根据实际情况判断采用合适的方法。

db.getCollection('topicAnls').find({})

db.getCollection('topicAnls').createIndex({"topicId": -1})

db.getCollection('topicAnls').getIndexes()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值