Navigation
This version of the manual is no longer supported.

distinct

distinct

The distinct command finds the distinct values for a specified field across a single collection. The command returns a document that contains an array of the distinct values as well as the query plan and status. The command takes the following prototype form:

{ distinct: collection, key: <field>, query: <query> }

The command fields are as follows:

Fields:
  • collection (String) – The name of the collection to query for distinct values.
  • field (string) – Specifies the field for which to return the distinct values.
  • query (document) – Optional. Specifies the selection query to determine the subset of documents from which to retrieve the distinct values.

Consider the following examples of the distinct command:

  • 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 } }
                    } )
    

Note

  • 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.
  • When possible, the distinct command will use an index to find the documents in the query as well as to return the data.