How to use limit method in MongoDB with examples

Published by admin on

MongoDB use limit method with examples

Introduction :

In this tutorial, we will learn how to use the limit() method in MongoDB with different examples. limit() method is used to fetch only a specific number of documents. This method takes one number, i.e. the number of documents that you want to fetch. You can use it on find().

limit() is useful if you want to fetch only a specific amount of result. It supports the following values :

 

Zero :

You can also use limit without setting any limit. It will return all documents if you don’t set any limit. If you pass zero, it is equivalent to no limit.

 

Negative values :

It also supports negative values. A negative number indicates that no more subsequent batch will be asked, i.e. the cursor will be closed after a single batch is returned. So, it is similar to positive values but the cursor is closed after the first batch is returned.

 

Positive values :

It supports any positive values.

Remember that it will work only for values within -2^31 and 2^31.

 

Example :

Let me show you with an example of how limit() works. I will show you by creating one new database, collection and new documents in that collection.

1. Start mongod :

Create one new folder db.Use the below command to start mongod with the database in a folder called db :

 mongod --dbpath ./db

It will start mongod pointing the database inside the folder db.

 

2. Start mongo :

Open one new terminal window and enter mongo command to start the mongoDB console.

 

3. Create DB and collection :

1. Create one DB :

 use users

2. Create one collection :

 db.createCollection("student")

3. Add documents to the collection :

 db.student.insertMany([{"name": "Alex","age" : 10},{"name": "Bob","age" : 10},{"name": "A
lbert","age" : 11},{"name": "Chandler","age" : 12},{"name": "Joey","age" : 11}])

The output of the above queries will look like as below :

MongoDB limit example

Now, we can get all documents with the below query :

db.student.find({})

It will return all the documents. To get only the first 2 documents, we can use the below query :

db.student.find({}).limit(2)

MongoDB limit example

We can also pass negative values to limit like below :

db.student.find({}).limit(-4)

MongoDB limit example

Categories: MongoDB

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *