Find Modifiers

find() modifiers are methods that modify behaviour of the cursor returned by the find() method. This chapter explains three main find modifiers, namely limit, skip and sort.

limit()

By default mongo shell takes the first 20 documents from the cursor of the find() method and prints it. The cursor can be iterated by typing "it" which gets the next 20 documents.

The limit() method sets the number of documents that a cursor should return. The syntax of limit() is as below

db.CollectionName.find().limit( n )

where n specifies the maximum number of documents the cursor can return.

skip()

The skip() method skips documents in a cursor there by controlling the starting point of the result set. The syntax of skip() is as below:

db.CollectionName.find().skip( n )

where n specifies the number of documents to be skipped.

sort()

The sort() methods sorts the documents in a cursor. The documents can be sorted in ascending or descending order on any field. The sort method takes a JSON style document as parameter to define the sort order on a field. The syntax is of sort() is as below:

db.CollectionName.find().sort( { field1: value, field2:value, ... } )

where value can be either -1 for descending or 1 for ascending order.

Find Modifier examples

Before you start these examples, create a test collection that contains many documents. This can be done easily by running a JavaScript program as shown below on the mongo shell.