• USA : +1 973 910 5725
  • INDIA: +91 905 291 3388
  • info@tekslate.com
  • Login

How to sort document in MongoDB

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.

Syntax:

Basic syntax of sort() method is given below

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

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

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

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.
>db.testCol.find({},{"title":1,_id:0}).sort({"title":-1})
{"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.

For indepth understanding click on

Summary
Review Date
Reviewed Item
How to sort document in MongoDB
Author Rating
5

“At TekSlate, we are trying to create high quality tutorials and articles, if you think any information is incorrect or want to add anything to the article, please feel free to get in touch with us at info@tekslate.com, we will update the article in 24 hours.”

0 Responses on How to sort document in MongoDB"

    Leave a Message

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

    Site Disclaimer, Copyright © 2016 - All Rights Reserved.

    Support


    Please leave a message and we'll get back to you soon.

    I agree to be contacted via e-mail.