|
| 1 | +========================================== |
| 2 | +Distinct Values of a Field in a Collection |
| 3 | +========================================== |
| 4 | + |
| 5 | +.. default-domain:: mongodb |
| 6 | + |
| 7 | +You can retrieve a list of distinct values for a field across a collection |
| 8 | +by using the `distinct() |
| 9 | +<https://mongodb.github.io/node-mongodb-native/3.4/api/Collection.html#distinct>`_ |
| 10 | +method. Call the ``distinct()`` method on a Collection object with |
| 11 | +a document field name parameter as a String to produce a list that contains |
| 12 | +one of each of the different values found in the specified document field. |
| 13 | + |
| 14 | +You can specify a document field within an *embedded document* using `dot |
| 15 | +notation |
| 16 | +<https://docs.mongodb.com/manual/core/document/#embedded-documents>`_. If |
| 17 | +you call ``distinct()`` on an document field that contains an array, each |
| 18 | +element of the array is treated as a separate value. |
| 19 | + |
| 20 | +You can provide an optional query document to narrow the set of documents that |
| 21 | +are searched and an optional Object to specify additional query parameters. |
| 22 | +For details on the optional parameters, see the |
| 23 | +`distinct() method in the API documentation |
| 24 | +<https://mongodb.github.io/node-mongodb-native/3.4/api/Collection.html#distinct>`_. |
| 25 | + |
| 26 | +The ``distinct()`` method returns a |
| 27 | +`Promise <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise>`_ |
| 28 | +that resolves to an |
| 29 | +`Array <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array>`_ |
| 30 | +that contains each of the different values. If none of the documents in the |
| 31 | +collection contain the field specified in the method call, it returns an |
| 32 | +empty Array. |
| 33 | + |
| 34 | +If you specify a value for the document field name that is not of type |
| 35 | +String such as a Document, Array, Number, or ``null``, the method does not |
| 36 | +execute and returns a TypeMismatch error with a message that resembles |
| 37 | +the following: |
| 38 | + |
| 39 | +:: |
| 40 | + |
| 41 | + "key" had the wrong type. Expected string, found <non-string type> |
| 42 | + |
| 43 | + |
| 44 | +Example |
| 45 | +------- |
| 46 | + |
| 47 | +The following snippet retrieves a list of distinct values for the ``year`` |
| 48 | +document field from the ``movies`` collection. It uses a query document to |
| 49 | +match only movies that include "Barbara Streisand" as a ``director``. |
| 50 | + |
| 51 | +.. literalinclude:: /code-snippets/usage-examples/distinct.js |
| 52 | + :language: javascript |
| 53 | + :linenos: |
0 commit comments