db.collection.distinct()

Definition

  • db.collection.distinct(field, query, options)

mongo Shell Method

This page documents the mongo shell method, and doesnot refer to the MongoDB Node.js driver (or any other driver)method. For corresponding MongoDB driver API, refer to your specificMongoDB driver documentation instead.

Finds the distinctvalues for a specified field across a single collection or view and returnsthe results in an array.

ParameterTypeDescriptionfieldstringThe field for which to return distinct values.querydocumentA query that specifies the documents from which to retrieve the distinct values.optionsdocumentOptional. A document that specifies the options. See Options.

The db.collection.distinct() method provides a wrapperaround the distinct command.

Note

Results must not be larger than the maximum BSON size. If your results exceed the maximumBSON size, use the aggregation pipeline to retrieve distinctvalues using the $group operator, as described inRetrieve Distinct Values with the Aggregation Pipeline.

Options

  1. { collation: <document> }
FieldTypeDescription
collationdocumentOptional.Specifies the collation to use for the operation.Collation allows users to specifylanguage-specific rules for string comparison, such as rules forlettercase and accent marks.The collation option has the following syntax:
  1. collation: { locale: <string>, caseLevel: <boolean>, caseFirst: <string>, strength: <int>, numericOrdering: <boolean>, alternate: <string>, maxVariable: <string>, backwards: <boolean>}
When specifying collation, the locale field is mandatory; allother collation fields are optional. For descriptions of the fields,see Collation Document.If the collation is unspecified but the collection has adefault collation (see db.createCollection()), theoperation uses the collation specified for the collection.If no collation is specified for the collection or for theoperations, MongoDB uses the simple binary comparison used in priorversions for string comparisons.You cannot specify multiple collations for an operation. Forexample, you cannot specify different collations per field, or ifperforming a find with a sort, you cannot use one collation for thefind and another for the sort.New in version 3.4.

Behavior

In a sharded cluster, the distinct command may returnorphaned documents.

Array Fields

If the value of the specified field is an array,db.collection.distinct() considers each element of the arrayas a separate value.

For instance, if a field has as its value [ 1, [1], 1 ], thendb.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 coverdb.collection.distinct() operations. See Covered Query for more informationon queries covered by indexes.

Transactions

To perform a distinct operation within a transaction:

To find the distinct values for a sharded collection, use theaggregation pipeline with the $group stage instead.See Distinct Operation for details.

Important

In most cases, multi-document transaction incurs a greaterperformance cost over single document writes, and theavailability of multi-document transactions should not be areplacement for effective schema design. For many scenarios, thedenormalized data model (embedded documents and arrays) will continue to be optimal for yourdata and use cases. That is, for many scenarios, modeling your dataappropriately will minimize the need for multi-documenttransactions.

For additional transactions usage considerations(such as runtime limit and oplog size limit), see alsoProduction Considerations.

Client Disconnection

Starting in MongoDB 4.2, if the client that issued the db.collection.distinct()disconnects before the operation completes, MongoDB marksthe db.collection.distinct() for termination (i.e. killOp on theoperation).

Examples

The examples use the inventory collection that contains thefollowing documents:

  1. { "_id": 1, "dept": "A", "item": { "sku": "111", "color": "red" }, "sizes": [ "S", "M" ] }
  2. { "_id": 2, "dept": "A", "item": { "sku": "111", "color": "blue" }, "sizes": [ "M", "L" ] }
  3. { "_id": 3, "dept": "B", "item": { "sku": "222", "color": "blue" }, "sizes": "S" }
  4. { "_id": 4, "dept": "A", "item": { "sku": "333", "color": "black" }, "sizes": [ "S" ] }

Return Distinct Values for a Field

The following example returns the distinct values for the fielddept from all documents in the inventory collection:

  1. db.inventory.distinct( "dept" )

The method returns the following array of distinct dept values:

  1. [ "A", "B" ]

Return Distinct Values for an Embedded Field

The following example returns the distinct values for the fieldsku, embedded in the item field, from all documents in theinventory collection:

  1. db.inventory.distinct( "item.sku" )

The method returns the following array of distinct sku values:

  1. [ "111", "222", "333" ]

See also

Dot Notation for information on accessing fieldswithin embedded documents

Return Distinct Values for an Array Field

The following example returns the distinct values for the fieldsizes from all documents in the inventory collection:

  1. db.inventory.distinct( "sizes" )

The method returns the following array of distinct sizes values:

  1. [ "M", "S", "L" ]

For information on distinct() and arrayfields, see the Behavior section.

Specify Query with distinct

The following example returns the distinct values for the fieldsku, embedded in the item field, from the documents whosedept is equal to "A":

  1. db.inventory.distinct( "item.sku", { dept: "A" } )

The method returns the following array of distinct sku values:

  1. [ "111", "333" ]

Specify a Collation

New in version 3.4.

Collation allows users to specifylanguage-specific rules for string comparison, such as rules forlettercase and accent marks.

A collection myColl has the following documents:

  1. { _id: 1, category: "café", status: "A" }
  2. { _id: 2, category: "cafe", status: "a" }
  3. { _id: 3, category: "cafE", status: "a" }

The following aggregation operation includes the Collationoption:

  1. db.myColl.distinct( "category", {}, { collation: { locale: "fr", strength: 1 } } )

For descriptions on the collation fields, seeCollation Document.