- Reference >
- Database Commands >
- Aggregation Commands >
- distinct
distinct¶
Definition¶
- distinct¶
Finds the distinct values for a specified field across a single collection. distinct returns a document that contains an array of the distinct values. The return document also contains a subdocument with query statistics and the query plan.
When possible, the distinct command uses an index to find documents and return values.
The command takes the following form:
{ distinct: "<collection>", key: "<field>", query: <query> }
The command contains the following fields:
Field Type Description distinct string The name of the collection to query for distinct values. key string The field to collect distinct values from. query document Optional. A query specification to limit the input documents in the distinct analysis.
Examples¶
Return an array of the distinct values of the field ord_dt from all documents in the orders collection:
db.runCommand ( { distinct: "orders", key: "ord_dt" } )
Return an array of the distinct values of the field sku in the subdocument item from all documents in the orders collection:
db.runCommand ( { distinct: "orders", key: "item.sku" } )
Return an array of the distinct values of the field ord_dt from the documents in the orders collection where the price is greater than 10:
db.runCommand ( { distinct: "orders",
key: "ord_dt",
query: { price: { $gt: 10 } }
} )
注解
MongoDB also provides the shell wrapper method db.collection.distinct() for the distinct command. Additionally, many MongoDB drivers also provide a wrapper method. Refer to the specific driver documentation.