Introduction to MongoDB $sortByCount Operator

The MongoDB $sortByCount operator is used to count and sort a field in all documents in a collection.

Syntax

The syntax of the $sortByCount operator is as follows:

{ $sortByCount: <expression> }

Where <expression> represents the field or expression to be counted.

Use cases

The $sortByCount operator is commonly used to count the occurrence of a field in a collection and sort it in descending order by count. This operator is useful for aggregation operations, especially when grouping, counting, and sorting by a field are required.

Examples

The following are two examples that demonstrate how to use the $sortByCount operator to count and sort data in a collection.

Example 1

Suppose there is an orders collection that stores information about orders from users. Each document contains a user ID and order amount. Now, the number of orders per user needs to be counted and sorted in descending order. The following aggregation operation can be used:

db.orders.aggregate([{ $sortByCount: "$userId" }])

The above operation groups all documents in the orders collection by the userId field, counts the number of documents in each group (i.e., the number of orders), and finally outputs the result in descending order by count.

Example 2

Suppose there is a students collection that stores information about students’ grades. Each document contains a student’s name, subject, and score. Now, the average score per subject needs to be calculated and sorted in descending order by the average score. The following aggregation operation can be used:

db.students.aggregate([
  {
    $group: {
      _id: "$subject",
      avgScore: { $avg: "$score" }
    }
  },
  { $sortByCount: "$avgScore" }
])

The above operation groups all documents in the students collection by the subject field, calculates the average score for each group, and finally outputs the result in descending order by the average score.

Conclusion

The $sortByCount operator is one of the useful aggregation operators in MongoDB, which makes it easy to count and sort a field in a collection. When aggregation operations are required, this operator can be considered for optimization.