How to sort document in MongoDB
  • Share this blog:

How to sort document in MongoDB

The sort() Method

We need to use sort() method to sort documents in MongoDB , it accepts a document field along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.


Basic syntax of sort() method is given below


Example: Point out the collection test Col has the following data

{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview", "by":""}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":" ASP.Net Over view ", "by":""}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":" SQL Server 2014", "by":""}

Following example will display the documents sorted by title in descending order.

Learn MongoDB by Tekslate - Fastest growing sector in the industry.
Explore Online MongoDB Training and course is aligned with industry needs & developed by industry veterans.
Tekslate will turn you into MongoDB Expert.
{"title":" SQL Server 2014"}
{"title":" MongoDB Overview "}
{"title":" SQL Server 2014"}

Note: if you don't specify the sorting preference, then sort() method will display documents in ascending order.


You liked the article?

Like : 0

Vote for difficulty

Current difficulty (Avg): Medium

Recommended Courses


About Author
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.

Stay Updated

Get stories of change makers and innovators from the startup ecosystem in your inbox