On this page
cursor.skip()
在本页面
Definition
cursor.
skip
(* *)- 在游标上调用cursor.skip()方法,以控制 MongoDB 从何处开始返回结果。此方法可能对实现分页结果有用。
Note
从数据库中检索任何文档之前,必须将cursor.skip()应用于光标。
cursor.skip()方法具有以下参数:
Parameter | Type | Description |
---|---|---|
offset |
number | 结果集中要跳过的文档数。 |
Pagination Example
Using cursor.skip()
以下 JavaScript 函数使用cursor.skip()在natural order中对集合进行分页:
function printStudents(pageNumber, nPerPage) {
print( "Page: " + pageNumber );
db.students.find()
.skip( pageNumber > 0 ? ( ( pageNumber - 1 ) * nPerPage ) : 0 )
.limit( nPerPage )
.forEach( student => {
print( student.name );
} );
}
cursor.skip()方法要求服务器从 Importing 结果集的开头开始扫描,然后再开始返回结果。随着偏移增加,cursor.skip()将变慢。
使用范围查询
范围查询可以使用indexes来避免扫描不需要的文档,与使用cursor.skip()进行分页相比,随着偏移量的增加,通常可以产生更好的性能。
Descending Order
使用以下过程可实现范围查询的分页:
选择一个诸如
_id
之类的字段,该字段通常会随着时间的推移而朝着一致的方向变化,并具有unique index来防止重复值,使用$lt和cursor.sort()运算符查询其字段小于起始值的文档,以及
存储下一个查询的最后一次查看的字段值。
例如,以下功能使用上述过程从集合中打印学生姓名的页面,首先使用_id
字段(即,以降序的 Sequences)以最新文档的 Sequences 对其进行排序:
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;
}
然后,您可以使用以下代码使用此分页功能来打印所有学生的姓名,并使用MaxKey从最大可能的键开始:
let currentKey = MaxKey;
while (currentKey !== null) {
currentKey = printStudents(currentKey, 10);
}
Note
Ascending Order
按升序返回分页结果与前一个相似,但使用$gt的升序排序 Sequences:
function printStudents(startValue, nPerPage) {
let endValue = null;
db.students.find( { _id: { $gt: startValue } } )
.sort( { _id: 1 } )
.limit( nPerPage )
.forEach( student => {
print( student.name );
endValue = student._id;
} );
return endValue;
}
同样使用此功能,但以MinKey作为起始键:
let currentKey = MinKey;
while (currentKey !== null) {
currentKey = printStudents(currentKey, 10);
}