Menu
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY CYBERSECURITY DATA SCIENCE
     ❯   

MongoDB Aggregation $sort


Aggregation $sort

This aggregation stage groups sorts all documents in the specified sort order.

Remember that the order of your stages matters. Each stage only acts upon the documents that previous stages provide.

Example

In this example, we are using the "sample_airbnb" database loaded from our sample data in the Intro to Aggregations section.

db.listingsAndReviews.aggregate([ 
  { 
    $sort: { "accommodates": -1 } 
  },
  {
    $project: {
      "name": 1,
      "accommodates": 1
    }
  },
  {
    $limit: 5
  }
])
Try it Yourself »

This will return the documents sorted in descending order by the accommodates field.

The sort order can be chosen by using 1 or -1. 1 is ascending and -1 is descending.