distinct

The `distinct` command is used to find the unique values for a specified field across a single collection. This command is useful when you need to identify the set of distinct values for a field without retrieving all the documents or when you need to perform operations like filtering or grouping based on unique values.

Retrieves distinct values for a specified field across a collection.

Syntax

db.collection.distinct(
  <field>,
  <query>,
  <options>
);

Parameters

fieldstringrequired

The field that receives the returned distinct values.

queryobject

A query that specifies the documents from which to retrieve the distinct values.

optionsobject

Other options for the command.

Examples

Sample Data

{
  "_id": "00000000-0000-0000-0000-000000001001",
  "name": "Example Store",
  "sales": {
    "salesByCategory": [
      {
        "categoryName": "Music Theory Books"
      },
      {
        "categoryName": "Superfoods"
      }
    ]
  },
  "promotionEvents": [
    {
      "eventName": "Summer Sale",
      "discounts": [
        {
          "categoryName": "Bath Sheets",
          "discountPercentage": 25
        }
      ]
    }
  ]
}

Find distinct categories in sales

To find the distinct `categoryName` in the `salesByCategory` array.

This query returns all unique category names from the sales data.

Query:

db.stores.distinct("sales.salesByCategory.categoryName")

Output:

[
  'Music Theory Books',
  'Superfoods',
  'Harmonicas',
  'Garden Tools',
  ... 883 more items
]

Find distinct event names in promotion events

To find the distinct `eventName` in the `promotionEvents` array.

This query returns all unique promotion event names.

Query:

db.stores.distinct("promotionEvents.eventName")

Output:

[
  'Super Saver Celebration',
  'Discount Derby',
  'Incredible Discount Days'
]

Find distinct discount percentages for a specific event

To find the distinct `discountPercentage` in the `discounts` array for the "Incredible Discount Days" event.

This query filters by event name and returns unique discount percentages for that event.

Query:

db.stores.distinct("promotionEvents.discounts.discountPercentage", { "promotionEvents.eventName": "Incredible Discount Days" })

Output:

[
   6, 17, 22, 25,  9, 15, 14,
   7, 12, 19, 24,  5, 20, 10,
  23, 16, 18, 21, 13, 11,  8
]

Related