Sometimes you might want to sort the order of the results returned in MongDB. By using of Sort() you will specifies the order in which the query returns matching documents. Sort direction can be 1 (ascending) or ?1 (descending). If multiple keys are given, the results will be sorted in that order.

Assume that we have the following documents in a collection.

> db.people.insert({"name" : "John", "age" : 38})
> db.people.insert({"name" : "Kelly", "age" : 26})
> db.people.insert({"name" : "Sarah", "age" : 36})

To sort based on the name in ascending order:

> db.people.find().sort({"name" : 1})
{ "_id" : ObjectId("53f1a7ecc94d4a349770bdc2"), "name" : "John", "age" : 38 }
{ "_id" : ObjectId("53f1a7f5c94d4a349770bdc3"), "name" : "Kelly", "age" : 26 }
{ "_id" : ObjectId("53f1a801c94d4a349770bdc4"), "name" : "Sarah", "age" : 36 }
To sort based on the name in descending order:
> db.people.find().sort({"name" : -1})
{ "_id" : ObjectId("53f1a801c94d4a349770bdc4"), "name" : "Sarah", "age" : 36 }
{ "_id" : ObjectId("53f1a7f5c94d4a349770bdc3"), "name" : "Kelly", "age" : 26 }
{ "_id" : ObjectId("53f1a7ecc94d4a349770bdc2"), "name" : "John", "age" : 38 }
To sort based on multiple key:
> db.people.find().sort({"age" : 1, "name" : -1})
{ "_id" : ObjectId("53f1a7f5c94d4a349770bdc3"), "name" : "Kelly", "age" : 26 }
{ "_id" : ObjectId("53f1a801c94d4a349770bdc4"), "name" : "Sarah", "age" : 36 }
{ "_id" : ObjectId("53f1a7ecc94d4a349770bdc2"), "name" : "John", "age" : 38 }