ThinkPHP操作MongoDB排序关于最大使用32M内存报错的解决方案

当mongodb里的数据达到一定规模以后,默认的32M内存已经无法存放这么大的数据而抛出错误,因为mongodb的排序是在内存中进行的,错误提示如下

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.

解决方案有两种

第一种是增加内存

db.adminCommand({setParameter:1, internalQueryExecMaxBlockingSortBytes:335544320})

这样内存就增加了10倍,但是不建议这么搞,我直接看第二种方法

第二种是索引排序

创建索引

db.聚合名.createIndex({ "字段":-1 }) #1是正序,-1是倒序
db.聚合名.getIndexes();

然后我们去语句中去吧sort语句中的key改为索引的key即可。


然后说明下thinkphp5对mongo进行排序的连贯操作order方法里面如果排序有多个条件字段,那么这么写

$map[] = ['id','>=',0];
$order = array("catid"=>-1,"inputtime"=>-1);
$data = Db::name('new')->where($map)->order($order)->paginate(10,false,['query'=>request()->param()]);

打印出来的结果是

string(106) "db.repo_man.find({"$and":[{"id":{"$gte":0}}]}).sort({"catid":-1,"inputtime":-1}).limit(10);"


内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://sulao.cn/post/556.html

我要评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。