In this MongoDB Tutorial – MongoDB Sort Documents, we shall learn to sort documents in a collection based on a field in ascending or descending order using cursor.sort() method with examples.

MongoDB Sort Documents

MongoDB Sort Documents – To sort documents in a collection based on a field, use cursor.sort() method. Sort method accepts Field and Order pairs in a document as argument. Field indicates that sorting of documents will occur based on the field specified and Order specifies the sorting order.

Syntax of sort() method

Following is the syntax of sort() method :

field [String] : any field name

order [Number] : 1 or -1 is allowed

OrderDescription
1Ascending (Increasing) Order
-1Descending (Decreasing) Order

Document to the sort() method is mandatory. But field:order pairs are optional. Which means, at the least sort() method expects an empty document.

Note : db.collection.find() returns cursor to the records. And sort() method can be applied on this cursor to sort the documents in increasing or decreasing order :

 

Example : Sort with a number field in ascending order

Documents are sorted in ascending order based on the field specified.

 

Example : Sort with no field:order specified

By default the documents are ordered by _id in ascending order.

 

Example : Sort with multiple filed:order pairs

The command db.customers.find().sort({"age":1,"name":1});  first sorted the documents based on age in ascending order, then the documents with same age value are sorted in ascending order.

The command db.customers.find().sort({"age":1,"name":-1});  first sorted the documents based on age in ascending order, then the documents with same age value are sorted in descending order.

 

Conclusion

In this tutorial – MongoDB Sort Documents, we have learnt to sort documents of a collection based on fields in ascending or descending order.