cursor.skip()

在本页面

Definition

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字段(即,以降序的 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

ObjectId值应随时间增加,但不一定是单调的。这是因为他们:

  • 仅包含一秒的时间分辨率,因此在同一秒内创建的ObjectId值没有保证的 Sequences,并且

  • 由 Client 端生成,Client 端可能具有不同的系统时钟。

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);
}
首页