MongoDB $sortByCount Aggregation Operator

In MongoDB the $sortByCount aggregation pipeline stage groups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group.

Each group is output in its own document, which consists of two fields:

  • an _id field containing the distinct grouping value, and
  • count field containing the number of documents belonging to that grouping.

The documents are sorted by count in descending order.

Example

Suppose we have a collection called pets with the following documents:

{ "_id" : 1, "name" : "Wag", "type" : "Dog", "weight" : 20 }
{ "_id" : 2, "name" : "Bark", "type" : "Dog", "weight" : 10 }
{ "_id" : 3, "name" : "Meow", "type" : "Cat", "weight" : 7 }
{ "_id" : 4, "name" : "Scratch", "type" : "Cat", "weight" : 8 }
{ "_id" : 5, "name" : "Bruce", "type" : "Bat", "weight" : 3 }
{ "_id" : 6, "name" : "Fetch", "type" : "Dog", "weight" : 17 }
{ "_id" : 7, "name" : "Jake", "type" : "Dog", "weight" : 30 }
{ "_id" : 8, "name" : "Tweet", "type" : "Bird", "weight" : 1 }
{ "_id" : 9, "name" : "Flutter", "type" : "Bird", "weight" : 2 }

Below is an example of a query that uses the $sortByCount operator.

db.pets.aggregate([ 
    { $match: {} }, 
    { $sortByCount: "$type" } 
])

Result:

{ "_id" : "Dog", "count" : 4 }
{ "_id" : "Cat", "count" : 2 }
{ "_id" : "Bird", "count" : 2 }
{ "_id" : "Bat", "count" : 1 }

In this example, we output each pet type, along with the number of pets of each respective type.

This is equivalent to the following:

db.pets.aggregate([
    {
      $match: { }
    },
    {
      $group: { _id: "$type", count: { $sum: 1 } }
    },
     { 
      $sort : { count : -1 } 
    }
])

Here’s another example, but with added filtering criteria.

db.pets.aggregate([
    {
      $match: { weight: { $lt: 15 } }
    },
    {
      $sortByCount: "$type"
    }
])

Result:

{ "_id" : "Cat", "count" : 2 }
{ "_id" : "Bird", "count" : 2 }
{ "_id" : "Dog", "count" : 1 }
{ "_id" : "Bat", "count" : 1 }

This time only one dog is in the document passed to $sortByCount, because the first pipeline stage removed dogs over a certain weight. Therefore, $sortByCount simply counts the numbers from the document provided to it, which included just one dog.

More Information

See the MongoDB documentation for more information.