This chapter introduces how to sort the query results in MongoDB, similar to the usage of MySQL's ORDER BY clause. Pagination in MongoDB is achieved through the sort function of the Cursor cursor.

Prepare test data

Insert a few records into the restaurants collection

db.restaurants.insertMany( [
   { "_id" : 1, "name" : "Central Park Cafe", "borough" : "Manhattan"},
   { "_id" : 2, "name" : "Rock A Feller Bar and Grill", "borough" : "Queens"},
   { "_id" : 3, "name" : "Empire State Pub", "borough" : "Brooklyn"},
   { "_id" : 4, "name" : "Stan's Pizzaria", "borough" : "Manhattan"},
   { "_id" : 5, "name" : "Jane's Deli", "borough" : "Brooklyn"},
] );

Sorting the Results

db.restaurants.find({}).sort({_id:1})

Explanation:

  • Use the sort function to set the sorting field.
  • Query all data and sort by _id in ascending order.

Format of the sort function parameters:

<field>: 1 or -1

Explanation:

  • 1 represents ascending order.
  • -1 represents descending order.

Combining with Pagination

db.restaurants.find({}).limit(2).skip(2).sort({_id:-1})

Explanation:

  • Query all data, return a maximum of 2 records, skip 2 records, and sort by _id in descending order.