最近使用skip和limit进行分页查询,当数据量增大时,发现响应时间不是很满意。
官方文档对skip的描述:
skip方法从结果集的开头进行扫描后返回查询结果。这样随着偏移的增加,skip将变得更慢
![](https://img.haomeiwen.com/i15486780/9498d3de7b20a8ec.png)
假设查询如下,随着数据量增大,查询速度会越来越慢
function printStudents(pageNumber, nPerPage) {
print( "Page: " + pageNumber );
db.students.find()
.skip( pageNumber > 0 ? ( ( pageNumber - 1 ) * nPerPage ) : 0 )
.limit( nPerPage )
.forEach( student => {
print( student.name );
} );
}
官方建议使用范围查询
范围查询可以使用[索引]分页相比,偏移量增加时通常会产生更好的性能。
指定开始位置
![](https://img.haomeiwen.com/i15486780/4a5818021242762e.png)
指定开始位置
function printStudents(startValue, nPerPage) {
let endValue = null;
db.students.find( { _id: { $lt: startValue } } )
.sort( { _id: -1 } )
.limit( nPerPage )
.forEach( student => {
print( student.name );
endValue = student._id;
} );
return endValue;
}
前后端结合,参考博客
https://www.cnblogs.com/woshimrf/p/mongodb-pagenation-performance.html
参考:
海量数据的分页怎么破?
网友评论