How to MongoDB- Sort, Skip, & Limit in MongoDB

In this tutorial, we are learning Sort, Skip, & Limit the documents in MongoDB. MongoDB will always perform them in the order of sort first, skip second, and limit last because that is the only order that makes sense.

 

Sort Documents

we are going to discuss how to sort data for one or more specific columns in ascending or descending order. To sort documents in MongoDB, we use sort() method. To specify sorting order 1 and -1 is used. 1 is used for ascending order while -1 is used for descending order.

Syntax
     db.COLLECTION_NAME.find().sort({KEY:1})

Example:

Consider the collection mycollection has the following data.

Example
     { "course": "MySQL", "category": "Database", "by": "lauyou.com" }, 
     { "course": "MongoDB", "category": "Database", "by": "lauyou" }, 
     { "course": "Java", "category": "Programming language", "by": "lauyou.com" }

 

Execute the following query to display the documents in descending order.

Query
     db.mycollections.find().sort({"course":-1})

This will show the documents in descending order.

Result
     {"_id" : ObjectId(3645369881331adf45ece), "course": "MySQL",  "category": "Database", "by": "lauyou" },
     {"_id" : ObjectId(3645369881331adf45ecd), "course": "MongoDB", "category": "Database", "by": "lauyou.com" },
     {"_id" : ObjectId(3645369881331adf45ecf), "course": "Java", "category": "Programming language", "by": "lauyou.com"}

 

Limit Method

The method accepts one number type argument, which is the number of documents that you want to be displayed. Sometimes, you have a lot of fields in the collection of your database and have to retrieve only 1 or 2. In such case, limit() method is used.

Syntax
     db.COLLECTION_NAME.find().limit(NUMBER)

 

Example:
     db.mycollection.find().limit(1)

After the execution, you will get the following result

Result
     {"_id" : ObjectId(3645369881331adf45ece), "course": "MySQL",  "category": "Database", "by": "lauyou" }

 

Skip document

skip() method is used to skip the document. It is used with find() and limit() methods.

Syntax
     db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
Example
     db.mycollection.find().limit(1).skip(2)

Above example skip first two records.

Result
     {"_id" : ObjectId(3645369881331adf45ecf), "course": "Java", "category": "Programming language", "by": "lauyou.com"}

 

Muhsin Yakkiparamban

Muhsin Yakkiparamban is the co-founder of Lauyou Learning. Muhsin holds Bachelor Degree in Civil Engineering from KMCT Calicut.

You may also like...