$sortByCount

The $sortByCount stage in the aggregation pipeline is used to group documents by a specified expression and then sort the count of documents in each group in descending order. The `$sortByCount` stage is useful for quickly identifying the most common values within a dataset.

Syntax

{
  $sortByCount: <expression>
}

Parameters

expressionstringrequired

The field or computed expression on which to group and count the documents.

Examples

Sample Data

{
  "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
  "name": "First Up Consultants | Beverage Shop",
  "promotionEvents": [
    { "eventName": "Unbeatable Bargain Bash" },
    { "eventName": "Steal of a Deal Days" }
  ]
}

Group and count by event name

Group promotion events by name and count occurrences in descending order.

This query identifies the most common promotional events.

Query:

db.stores.aggregate([
  { $unwind: "$promotionEvents" },
  { $sortByCount: "$promotionEvents.eventName" }
])

Output:

[
  { "_id": "Crazy Deal Days", "count": 4239 },
  { "_id": "Markdown Madness", "count": 2967 },
  { "_id": "Bargain Bonanza", "count": 2925 },
  { "_id": "Crazy Discount Days", "count": 2922 },
  { "_id": "Price Smash Spectacular", "count": 2915 }
]

Related