OPTIONS
翻译或纠错本页面

db.collection.distinct()

Definition

db.collection.distinct(field, query)

Finds the distinct values for a specified field across a single collection and returns the results in an array.

Parameter Type Description
field string The field for which to return distinct values.
query document A query that specifies the documents from which to retrieve the distinct values.

The db.collection.distinct() method provides a wrapper around the distinct command. Results must not be larger than the maximum BSON size.

When possible to use covered indexes, the db.collection.distinct() method will use an index to find the documents in the query as well as to return the data.

Examples

The following are examples of the db.collection.distinct() method:

  • Return an array of the distinct values of the field ord_dt from all documents in the orders collection:

    db.orders.distinct( '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.orders.distinct( '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.orders.distinct( 'ord_dt', { price: { $gt: 10 } } )