- Reference >
- Database Commands >
- Aggregation Commands >
- distinct
distinct¶
On this page
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 an embedded document with query statistics and the query plan.The command takes the following form
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 for which to return distinct values. query
document Optional. A query that specifies the documents from which to retrieve the distinct values. readConcern
document Optional. Specifies the read concern.
Starting in MongoDB 3.6, the readConcern option has the following syntax:
readConcern: { level: <value> }
Possible read concern levels are:
"local"
. This is the default read concern level for read operations against primary and read operations against secondaries when associated with causally consistent sessions."available"
. This is the default for reads against secondaries when when not associated with causally consistent sessions. The query returns the instance’s most recent data."majority"
. Available for replica sets that use WiredTiger storage engine."linearizable"
. Available for read operations on theprimary
only.
For more formation on the read concern levels, see Read Concern Levels.
collation
document Optional.
Specifies the collation to use for the operation.
Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.
The collation option has the following syntax:
When specifying collation, the
locale
field is mandatory; all other collation fields are optional. For descriptions of the fields, see Collation Document.If the collation is unspecified but the collection has a default collation (see
db.createCollection()
), the operation uses the collation specified for the collection.If no collation is specified for the collection or for the operations, MongoDB uses the simple binary comparison used in prior versions for string comparisons.
You cannot specify multiple collations for an operation. For example, you cannot specify different collations per field, or if performing a find with a sort, you cannot use one collation for the find and another for the sort.
New in version 3.4.
comment
any Optional. A user-provided comment to attach to this command. Once set, this comment appears alongside records of this command in the following locations:
- mongod log messages, in the
attr.command.cursor.comment
field. - Database profiler output, in the
command.comment
field. currentOp
output, in thecommand.comment
field.
A comment can be any valid BSON type (string, integer, object, array, etc).
New in version 4.4.
Note
Results must not be larger than the maximum BSON size. If your results exceed the maximum BSON size, use the aggregation pipeline to retrieve distinct values using the
$group
operator, as described in Retrieve Distinct Values with the Aggregation Pipeline.MongoDB also provides the shell wrapper method
db.collection.distinct()
for thedistinct
command. Additionally, many MongoDB drivers provide a wrapper method. Refer to the specific driver documentation.
Behavior¶
In a sharded cluster, the distinct
command may return
orphaned documents.
Array Fields¶
If the value of the specified field
is an array,
distinct
considers each element of the array
as a separate value.
For instance, if a field has as its value [ 1, [1], 1 ]
, then
distinct
considers 1
, [1]
, and 1
as separate values.
For an example, see Return Distinct Values for an Array Field.
Index Use¶
When possible, distinct
operations can use indexes.
Indexes can also cover
distinct
operations. See Covered Query for more information
on queries covered by indexes.
Transactions¶
To perform a distinct operation within a transaction:
For unsharded collections, you can use the
db.collection.distinct()
method/thedistinct
command as well as the aggregation pipeline with the$group
stage.For sharded collections, you cannot use the
db.collection.distinct()
method or thedistinct
command.To find the distinct values for a sharded collection, use the aggregation pipeline with the
$group
stage instead. See Distinct Operation for details.
Important
In most cases, multi-document transaction incurs a greater performance cost over single document writes, and the availability of multi-document transactions should not be a replacement for effective schema design. For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your data and use cases. That is, for many scenarios, modeling your data appropriately will minimize the need for multi-document transactions.
For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.
Client Disconnection¶
Starting in MongoDB 4.2, if the client that issued the distinct
disconnects before the operation completes, MongoDB marks
the distinct
for termination (i.e. killOp
on the
operation).
Replica Set Member State Restriction¶
Starting in MongoDB 4.4, to run on a replica set member,
distinct
operations require the member to be in
PRIMARY
or SECONDARY
state. If the member
is in another state, such as STARTUP2
, the
operation errors.
In previous versions, the operations can also be run when the member
is in STARTUP2
. However, the operations wait
until the member transitions to RECOVERING
.
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 command returns a document with a field named values
that
contains the 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 command returns a document with a field named values
that
contains the 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 command returns a document with a field named values
that
contains the 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 command returns a document with a field named values
that
contains the distinct sku
values:
Specify a Collation¶
New in version 3.4.
Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.
A collection myColl
has the following documents:
The following aggregation operation includes the Collation option:
For descriptions on the collation fields, see Collation Document.
Override Default Read Concern¶
To override the default read concern level of "local"
,
use the readConcern
option.
The following operation on a replica set specifies a
Read Concern of "majority"
to read the
most recent copy of the data confirmed as having been written to a
majority of the nodes.
Note
To use read concern level of
"majority"
, replica sets must use WiredTiger storage engine.You can disable read concern
"majority"
for a deployment with a three-member primary-secondary-arbiter (PSA) architecture; however, this has implications for change streams (in MongoDB 4.0 and earlier only) and transactions on sharded clusters. For more information, see Disable Read Concern Majority.Regardless of the read concern level, the most recent data on a node may not reflect the most recent version of the data in the system.
To ensure that a single thread can read its own writes, use
"majority"
read concern and "majority"
write concern against the primary of the replica set.