- Reference >
mongoShell Methods >- Collection Methods >
- db.collection.distinct()
db.collection.distinct()¶
On this page
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 fieldstring The field for which to return distinct values. querydocument A query that specifies the documents from which to retrieve the distinct values. The
db.collection.distinct()method provides a wrapper around thedistinctcommand. Results must not be larger than the maximum BSON size.
Behavior¶
Array Fields¶
If the value of the specified field is an array,
db.collection.distinct() considers each element of the array
as a separate value.
For instance, if a field has as its value [ 1, [1], 1 ], then
db.collection.distinct() considers 1, [1], and 1 as separate values.
For an example, see Return Distinct Values for an Array Field.
Index Use¶
When possible, db.collection.distinct() operations can use indexes.
Indexes can also cover
db.collection.distinct() operations. See Covering a Query for more information
on queries covered by indexes.
Examples¶
The examples use the inventory collection that contains the
following documents:
Return Distinct Values for a Field¶
The following example returns the distinct values for the field
dept from all documents in the inventory collection:
The method returns the following array of distinct dept values:
Return Distinct Values for an Embedded Field¶
The following example returns the distinct values for the field
sku, embedded in the item field, from all documents in the
inventory collection:
The method returns the following array of distinct sku values:
See also
Dot Notation for information on accessing fields within embedded documents
Return Distinct Values for an Array Field¶
The following example returns the distinct values for the field
sizes from all documents in the inventory collection:
The method returns the following array of distinct sizes values:
For information on distinct() and array
fields, see the Behavior section.
Specify Query with distinct¶
The following example returns the distinct values for the field
sku, embedded in the item field, from the documents whose
dept is equal to "A":
The method returns the following array of distinct sku values: