Introduction to MongoDB cursor.skip() Method

In MongoDB, the cursor.skip() method can be used to skip the first N documents in a query result and return the subsequent documents. This method returns a new cursor object that can be used to perform further operations, such as limiting, sorting, projection, etc., on the skipped documents.

Syntax

db.collection.find().skip(N)

The parameter N represents the number of documents to skip, and should be a non-negative integer.

Use cases

The cursor.skip() method can be used in the following scenarios:

  • When paging through a large number of documents, this method can be used to implement paging. For example, to query documents 11 to 20, use cursor.skip(10).limit(10).
  • When the first few documents in the query result are known and it is desired to start getting results from the next document, this method can be used to skip the known documents.

It should be noted that the cursor.skip() method is not suitable for skipping a large number of documents, as it needs to skip the specified number of documents before returning the result, which can result in decreased query performance.

Examples

Here are two examples of using the cursor.skip() method:

Example 1

Suppose there is a collection named users containing the following documents:

{ _id: 1, name: "Alice" }
{ _id: 2, name: "Bob" }
{ _id: 3, name: "Charlie" }
{ _id: 4, name: "David" }
{ _id: 5, name: "Eve" }

To query documents 3 to 4 in the users collection, use the following command:

db.users.find().skip(2).limit(2)

The output of this command is:

{ _id: 3, name: "Charlie" }
{ _id: 4, name: "David" }

Example 2

Suppose the first two documents in the users collection are known, with _id values of 1 and 2. To query all documents starting from the third document, use the following command:

db.users.find({ _id: { $gt: 2 } })

The output of this command is:

{ _id: 3, name: 'Charlie' }
{ _id: 4, name: 'David' }
{ _id: 5, name: 'Eve' }

Conclusion

The cursor.skip() method is a useful tool for skipping the first N documents in a query result. However, it should be used sparingly when dealing with a large number of documents, as it may result in decreased query performance.