distinct (original) (raw)
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.
Tip
In mongosh, this command can also be run through the db.collection.distinct() helper method.
Helper methods are convenient for mongosh users, but they may not return the same level of information as database commands. In cases where the convenience is not needed or the additional return fields are required, use the database command.
This command is available in deployments hosted in the following environments:
- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
Important
This command has limited support in M0, M2, M5, and Flex clusters. For more information, see Unsupported Commands.
- MongoDB Enterprise: The subscription-based, self-managed version of MongoDB
- MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB
The command has the following syntax:
db.runCommand(
{
distinct: "<collection>",
key: "<field>",
query: <query>,
readConcern: <read concern document>,
collation: <collation document>,
comment: <any>,
hint: <string or document>
}
)
The command takes 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.The readConcern option has the following syntax:readConcern: { level: }Possible read concern levels are:"local". This is the default read concern level for read operations against the primary and secondaries."available". Available for read operations against the primary and secondaries. "available" behaves the same as "local" against the primary and non-sharded secondaries. The query returns the instance's most recent data."majority". Available for replica sets that useWiredTiger storage engine."linearizable". Available for read operations on theprimary only."snapshot". Available for multi-document transactions, and starting in MongoDB 5.0, certain read operations outside of multi-document transactions.For more formation on the read concern levels, seeRead 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:collation: { locale: , caseLevel: , caseFirst: , strength: , numericOrdering: , alternate: , maxVariable: , backwards: }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. |
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 theattr.command.cursor.comment field.Database profiler output, in the command.comment field.currentOp output, in the command.comment field.A comment can be any valid BSON type(string, integer, object, array, etc). |
hint | string or document | Optional. Specify the index name, either as a string or a document. If specified, the query planner only considers plans using the hinted index. For more details, see Specify an Index.New in version 7.1. |
Note
MongoDB also provides the shell wrapper methoddb.collection.distinct() for the distinctcommand. Additionally, many MongoDB driversprovide a wrapper method. Refer to the specific driver documentation.
In a sharded cluster, the distinct command may returnorphaned documents.
For time series collections, thedistinct
command can't make efficient use of indexes. Instead, use a$group aggregation to group documents by distinct values. For details, see Time Series Limitations.
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 ]
, thendistinct considers 1
, [1]
, and 1
as separate values.
Starting in MongoDB 6.0, the distinct command returns the same results for collections and views when using arrays.
For examples, see:
When possible, distinct operations can use indexes.
Indexes can also cover distinct operations. See Covered Query for more information on queries covered by indexes.
To perform a distinct operation within a transaction:
- For unsharded collections, you can use thedb.collection.distinct() method/thedistinct command as well as the aggregation pipeline with the $group stage.
- For sharded collections, you cannot use thedb.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, a distributed transaction incurs a greater performance cost over single document writes, and the availability of distributed transactions should not be a replacement for effective schema design. For many scenarios, thedenormalized 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 distributed transactions.
For additional transactions usage considerations (such as runtime limit and oplog size limit), see alsoProduction Considerations.
Starting in MongoDB 4.2, if the client that issued distinctdisconnects before the operation completes, MongoDB marks distinctfor termination using killOp.
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.
Starting in MongoDB 6.0, an index filter uses the collation previously set using the planCacheSetFiltercommand.
Starting in MongoDB 8.0, use query settings instead of addingindex filters. Index filters are deprecated starting in MongoDB 8.0.
Query settings have more functionality than index filters. Also, index filters aren't persistent and you cannot easily create index filters for all cluster nodes. To add query settings and explore examples, seesetQuerySettings.
New in version 8.0.
You can use query settings to set index hints, set operation rejection filters, and other fields. The settings apply to the query shape on the entire cluster. The cluster retains the settings after shutdown.
The query optimizer uses the query settings as an additional input during query planning, which affects the plan selected to run the query. You can also use query settings to block a query shape.
To add query settings and explore examples, seesetQuerySettings.
You can add query settings for find, distinct, and aggregate commands.
Query settings have more functionality and are preferred over deprecated index filters.
To remove query settings, use removeQuerySettings. To obtain the query settings, use a $querySettings stage in an aggregation pipeline.
The examples use the inventory
collection that contains the following documents:
{ "_id": 1, "dept": "A", "item": { "sku": "111", "color": "red" }, "sizes": [ "S", "M" ] }
{ "_id": 2, "dept": "A", "item": { "sku": "111", "color": "blue" }, "sizes": [ "M", "L" ] }
{ "_id": 3, "dept": "B", "item": { "sku": "222", "color": "blue" }, "sizes": "S" }
{ "_id": 4, "dept": "A", "item": { "sku": "333", "color": "black" }, "sizes": [ "S" ] }
The following example returns the distinct values for the fielddept
from all documents in the inventory
collection:
db.runCommand ( { distinct: "inventory", key: "dept" } )
The command returns a document with a field named values
that contains the distinct dept
values:
{
"values" : [ "A", "B" ],
"ok" : 1
}
The following example returns the distinct values for the fieldsku
, embedded in the item
field, from all documents in theinventory
collection:
db.runCommand ( { distinct: "inventory", key: "item.sku" } )
The command returns a document with a field named values
that contains the distinct sku
values:
{
"values" : [ "111", "222", "333" ],
"ok" : 1
}
See also:
Dot Notation for information on accessing fields within embedded documents
The following example returns the distinct values for the fieldsizes
from all documents in the inventory
collection:
db.runCommand ( { distinct: "inventory", key: "sizes" } )
The command returns a document with a field named values
that contains the distinct sizes
values:
{
"values" : [ "M", "S", "L" ],
"ok" : 1
}
For information on distinct and array fields, see theBehavior section.
Starting in MongoDB 6.0, the distinct command returns the same results for collections and views when using arrays.
The following example creates a collection named sensor
with an array of temperature values for each document:
db.sensor.insertMany( [
{ _id: 0, temperatures: [ { value: 1 }, { value: 4 } ] },
{ _id: 1, temperatures: [ { value: 2 }, { value: 8 } ] },
{ _id: 2, temperatures: [ { value: 3 }, { value: 12 } ] },
{ _id: 3, temperatures: [ { value: 1 }, { value: 4 } ] }
] )
The following example creates a view named sensorView
from thesensor
collection:
db.createView( "sensorView", "sensor", [] )
The following example uses distinct to return the unique values from the temperatures
array in the sensor
collection:
db.sensor.distinct( "temperatures.1.value" )
The 1
in temperatures.1.value
specifies the temperatures
array index.
Example output:
Example for sensorView
:
db.sensorView.distinct( "temperatures.1.value" )
Example output:
[ 4, 8, 12 ]
starting in MongoDB 6.0 (identical to result returned from thesensor
collection).[]
in MongoDB versions earlier than 6.0.
The following example returns the distinct values for the fieldsku
, embedded in the item
field, from the documents whosedept
is equal to "A"
:
db.runCommand ( { distinct: "inventory", key: "item.sku", query: { dept: "A"} } )
The command returns a document with a field named values
that contains the distinct sku
values:
{
"values" : [ "111", "333" ],
"ok" : 1
}
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:
{ _id: 1, category: "café", status: "A" }
{ _id: 2, category: "cafe", status: "a" }
{ _id: 3, category: "cafE", status: "a" }
The following aggregation operation includes the Collationoption:
db.runCommand(
{
distinct: "myColl",
key: "category",
collation: { locale: "fr", strength: 1 }
}
)
For descriptions on the collation fields, seeCollation Document.
To override the default read concern level of "local", use the readConcern
option.
The following operation on a replica set specifies aRead Concern of "majority" to read the most recent copy of the data confirmed as having been written to a majority of the nodes.
Note
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.
db.runCommand(
{
distinct: "restaurants",
key: "rating",
query: { cuisine: "italian" },
readConcern: { level: "majority" }
}
)
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.
You can specify an index name or pattern using the hint option.
To specify a hint based on an index name:
db.runCommand ( { distinct: "inventory", key: "dept", hint: "sizes" } )
To specify a hint based on an index pattern:
db.runCommand ( { distinct: "inventory", key: "dept", hint: { sizes: 1 } } )