|

MongoDB – Sort Records

You need to use the sort() method in trying to process documents in MongoDB.

The sort() method specifies how the query returns matching documents from the given collection. Before retrieving any documents from the database, you must apply this method to the cursor. It accepts as a parameter a document containing a field: value pair that defines the sort order of the result set. The values 1 and -1 indicate ascending or descending sorting, respectively.

  • If a sort returns the same result every time we perform on the same data, then such type of sort is known as a stable sort. 
  • If a sort returns a different result every time we perform on the same data, then such type of sort is known as an unstable sort.
  • MongoDB generally performs a stable sort unless sorting on a field that holds duplicate values.  
  • We can use limit() method with sort() method, it will return the first m documents, where m is the given limit.
  • MongoDB can find the result of the sort operation using indexes.
  • If MongoDB does not find sort order using index scanning, then it uses top-k sort algorithm. 

Syntax

The basic syntax of sort() method is as follows −

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

Example

Consider the collection myycol has the following data.

{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"}
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"}
{_id : ObjectId("507f191e810c19729de860e3"), title: "Codelivly  Overview"}
>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})
{"title":"Codelivly Overview"}
{"title":"NoSQL Overview"}
{"title":"MongoDB Overview"}
>

Similar Posts

Leave a Reply

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