MongoDB

MongoDB limit() and skip() Example

Hello readers, in this tutorial, we will see the limit() and the skip() methods available in the Mongo database.

1. Introduction

If you have installed the MongoDB application (version 3.6) on Windows or Ubuntu operating system and you wish to learn the limit() and the skip() methods then follow the below steps. It is very simple, but before moving further let’s take a look at the Mongo database and its characteristics.

1.1 What is MongoDB?

  • MongoDB is a high-performance NoSQL database where each database has collections which in turn has documents. Each document has a different number of fields, size, content, and is stored in a JSON-like format (i.e. Binary JSON (BSN))
  • The documents in MongoDB doesn’t need to have a schema defined beforehand. Instead, the fields (i.e. records) can be created on the go
  • Data model available within the MongoDB allows developers to represent the hierarchical relationships, store arrays, and other more complex structures easily
  • This NoSQL solution often comes with embedding, auto-sharding, and onboard replication for better scalability and high availability

1.1.1 Why MongoDB?

  • As a NoSQL type database, MongoDB stores the data in the form of a document. Thus, MongoDB offers more flexibility
  • This database supports search by field-name, range queries, and the regular expressions. It often provides queries to return the particular fields inside the documents
  • MongoDB offers indexes to improve the search performance within the NoSQL database
  • To offer horizontal scalability, MongoDB uses sharding by splitting the data across the many MongoDB occurrences
  • Replication: MongoDB can give high availability with the replica sets

1.2 What is a Cursor in MongoDB?

In Mongo world, a cursor is an object that allows developers to iterate through the documents of a Mongo collection. The behavior of cursor allows an automatic iteration across the results of the query; however, developers can explicitly go through the items returned in the cursor object. The below diagram lists 4 documents where the Mongo cursor will point to the first document and then iterate through all the other documents of a collection.

Fig. 1: Pictorial representation of a Cursor in Mongo collection
Fig. 1: Pictorial representation of a Cursor in Mongo collection

1.2.1 Why Cursor in MongoDB?

Cursor offers:

  • A true snapshot of a system i.e. it returns the data in batches and increases the database performance
  • It saves system memory by allowing batch inserts and updates
  • Intelligibility and Clarity on the ad-hoc and complex queries of the sequential nature having large result sets and low consistency requirements
  • Openness to work on small batches of data as developers don’t need to wait for the processing and download of the complete record-set

2. MongoDB limit() and skip() Example

In this tutorial, we will learn how to handle the limit() and the skip() methods provided by the Mongo database.

2.1 limit() method in the Mongo database

In the Mongo universe, the limit() method specifies the number of documents returned in response to a particular Mongo query i.e. developers can append the limit() method to the db.collection_name.find() query. The cursor.limit() method has the following prototype form:

Mongo database ‘limit()’ Syntax

> db.collection_name.find(<query_string>).limit(<number>)

Where:

  • The query_string is an optional input argument that retrieves the documents from a collection on the basis of a specified choice criteria
  • The number is an input integer argument that specifies the maximum number of documents to be returned

Do remember:

  • The limit() method is undefined for the values less than -231 and greater than 231
  • An input argument of 0 is equal to set no limit on the limit() method

2.2 skip() method in the Mongo database

In the Mongo universe, the skip() method skips the given number of the documents within the cursor object. In other words, developers can control from where the Mongo database begins returning the results and the cursor.skip() method has the following prototype form:

Mongo database ‘skip()’ Syntax

> db.collection_name.find(<query_string>).limit(<number>).skip(<offset>)

Where:

  • The query_string is an optional input argument that retrieves the documents from a collection on the basis of a specified choice criteria
  • The number is an input integer argument that specifies the maximum number of documents to be returned
  • The offset is an input integer argument that specifies the number of documents to be skipped in a result set

2.3 Practical usage

Let’s understand the implementation of these methods with the help of the sample snippets.

2.3.1 Start MongoDB

Start a standalone mongod instance as shown below.

Fig. 2: Start Mongo instance
Fig. 2: Start Mongo instance

2.3.2 Connect to the Mongo Instance

Connect with the mongo shell to make a connection with the MongoDB instance on the port 27017 as shown below.

Fig. 3: Connect to Mongo database
Fig. 3: Connect to Mongo database

2.3.3 Create Mongo database and collection

To begin with the implementation, we will need to create a sample database and collection. The below script creates a database called places with a collection of restaurants. Open the Mongo terminal and execute the script.

Database & Collection creation script

> use places

> db.restaurants.insertMany( [
	{"address": {"building": "1007", "coord": [-73.856077, 40.848447], "street": "Morris Park Ave", "zipcode": "10462"}, "borough": "Bronx", "cuisine": "Bakery", "grades": [{"date": {"$date": 1393804800000}, "grade": "A", "score": 2}, {"date": {"$date": 1378857600000}, "grade": "A", "score": 6}, {"date": {"$date": 1358985600000}, "grade": "A", "score": 10}, {"date": {"$date": 1322006400000}, "grade": "A", "score": 9}, {"date": {"$date": 1299715200000}, "grade": "B", "score": 14}], "name": "Morris Park Bake Shop", "restaurant_id": "30075445"},
	{"address": {"building": "469", "coord": [-73.961704, 40.662942], "street": "Flatbush Avenue", "zipcode": "11225"}, "borough": "Brooklyn", "cuisine": "Hamburgers", "grades": [{"date": {"$date": 1419897600000}, "grade": "A", "score": 8}, {"date": {"$date": 1404172800000}, "grade": "B", "score": 23}, {"date": {"$date": 1367280000000}, "grade": "A", "score": 12}, {"date": {"$date": 1336435200000}, "grade": "A", "score": 12}], "name": "Wendy'S", "restaurant_id": "30112340"},
	{"address": {"building": "351", "coord": [-73.98513559999999, 40.7676919], "street": "West   57 Street", "zipcode": "10019"}, "borough": "Manhattan", "cuisine": "Irish", "grades": [{"date": {"$date": 1409961600000}, "grade": "A", "score": 2}, {"date": {"$date": 1374451200000}, "grade": "A", "score": 11}, {"date": {"$date": 1343692800000}, "grade": "A", "score": 12}, {"date": {"$date": 1325116800000}, "grade": "A", "score": 12}], "name": "Dj Reynolds Pub And Restaurant", "restaurant_id": "30191841"},
	{"address": {"building": "2780", "coord": [-73.98241999999999, 40.579505], "street": "Stillwell Avenue", "zipcode": "11224"}, "borough": "Brooklyn", "cuisine": "American ", "grades": [{"date": {"$date": 1402358400000}, "grade": "A", "score": 5}, {"date": {"$date": 1370390400000}, "grade": "A", "score": 7}, {"date": {"$date": 1334275200000}, "grade": "A", "score": 12}, {"date": {"$date": 1318377600000}, "grade": "A", "score": 12}], "name": "Riviera Caterer", "restaurant_id": "40356018"},
	{"address": {"building": "97-22", "coord": [-73.8601152, 40.7311739], "street": "63 Road", "zipcode": "11374"}, "borough": "Queens", "cuisine": "Jewish/Kosher", "grades": [{"date": {"$date": 1416787200000}, "grade": "Z", "score": 20}, {"date": {"$date": 1358380800000}, "grade": "A", "score": 13}, {"date": {"$date": 1343865600000}, "grade": "A", "score": 13}, {"date": {"$date": 1323907200000}, "grade": "B", "score": 25}], "name": "Tov Kosher Kitchen", "restaurant_id": "40356068"},
	{"address": {"building": "8825", "coord": [-73.8803827, 40.7643124], "street": "Astoria Boulevard", "zipcode": "11369"}, "borough": "Queens", "cuisine": "American ", "grades": [{"date": {"$date": 1416009600000}, "grade": "Z", "score": 38}, {"date": {"$date": 1398988800000}, "grade": "A", "score": 10}, {"date": {"$date": 1362182400000}, "grade": "A", "score": 7}, {"date": {"$date": 1328832000000}, "grade": "A", "score": 13}], "name": "Brunos On The Boulevard", "restaurant_id": "40356151"},
	{"address": {"building": "7114", "coord": [-73.9068506, 40.6199034], "street": "Avenue U", "zipcode": "11234"}, "borough": "Brooklyn", "cuisine": "Delicatessen", "grades": [{"date": {"$date": 1401321600000}, "grade": "A", "score": 10}, {"date": {"$date": 1389657600000}, "grade": "A", "score": 10}, {"date": {"$date": 1375488000000}, "grade": "A", "score": 8}, {"date": {"$date": 1342569600000}, "grade": "A", "score": 10}, {"date": {"$date": 1331251200000}, "grade": "A", "score": 13}, {"date": {"$date": 1318550400000}, "grade": "A", "score": 9}], "name": "Wilken'S Fine Food", "restaurant_id": "40356483"},
	{"address": {"building": "6409", "coord": [-74.00528899999999, 40.628886], "street": "11 Avenue", "zipcode": "11219"}, "borough": "Brooklyn", "cuisine": "American ", "grades": [{"date": {"$date": 1405641600000}, "grade": "A", "score": 12}, {"date": {"$date": 1375142400000}, "grade": "A", "score": 12}, {"date": {"$date": 1360713600000}, "grade": "A", "score": 11}, {"date": {"$date": 1345075200000}, "grade": "A", "score": 2}, {"date": {"$date": 1313539200000}, "grade": "A", "score": 11}], "name": "Regina Caterers", "restaurant_id": "40356649"}
] )

The script gives the below output.

Fig. 4: Database & Collection creation
Fig. 4: Database & Collection creation

2.3.4 Check Mongo database and collection

If the script works well, the database and the collection will be shown in the Mongo Workbench. Using the db.collection_name.find() or the db.collection_name.find().pretty() command the documents of a collection will be shown as below.

Fig. 5: Mongo database & collection
Fig. 5: Mongo database & collection

2.3.5 Implementation of ‘limit()’ method

Now, go back to the Mongo shell and use the limit(<number>) method to fetch the first three documents from the restaurants collection. The following Mongo database command can be used.

Query 1

> db.restaurants.find().limit(3)

This command will show the first three documents retrieved from the restaurants collection.

Fig. 6: Mongo database limit() method
Fig. 6: Mongo database limit() method

Let’s say developers want to return the documents by specifying a query string. They can do this by simply appending the query_string in the find() method. The following Mongo database command can be used.

Query 1(a)

> db.restaurants.find( { cuisine: "American " } ).limit(2)

This command will show the first two documents from the restaurants collection that matches the specified choice criteria.

Fig. 7: Mongo database limit() method with a Search query
Fig. 7: Mongo database limit() method with a Search query

2.3.6 Implementation of ‘skip()’ method

To understand the usage of skip() method, let’s take the same example. In the above example, developers can see that by using the limit(2) method we managed to get only two documents. What if developers do not want the first document that matches the specified criteria? For e.g. we have three documents that match the criteria. We limited the search results to 2 by using the limit(2) method. In order to get the third document matching this criterion, developers can use the skip(2) method.

Query 2

> db.restaurants.find( { cuisine: "American " } ).skip(2)

This command will skip the first two Mongo documents and will end up with the last document. Do note, the search string specified in Query 2 is an optional argument.

Fig. 8: Mongo database skip() method with a Search query
Fig. 8: Mongo database skip() method with a Search query

2.3.7 Implementation of ‘limit()’ and ‘skip()’ methods

Let’s say developers want to fetch the two documents after the first document is skipped from the restaurants collection. The following Mongo database command can be used.

Query 3

> db.restaurants.find().skip(1).limit(2)

This command will skip the first document from the restaurants collection and displays the other two.

Fig. 9: Mongo database limit() and skip() methods
Fig. 9: Mongo database limit() and skip() methods

That’s all for this post. Happy Learning!!

3. Conclusion

In this tutorial, we learned about the limit() and the skip() methods of the Mongo database. Developers can download the sample commands in the Downloads section.

4. Download the Eclipse Project

This was an example of the limit() and the skip() methods available in the Mongo database.

Download
You can download the full source code of this example here: CodeSnippet

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button