@@ -4,11 +4,215 @@ Sort Results
44
55.. default-domain:: mongodb
66
7- Use ``sort()`` to change the order in which read operations return
8- documents. The ``sort()`` instance method tells MongoDB to order returned documents by the
9- values of one or more fields in a certain direction. To sort returned
10- documents by a field in ascending (lowest first) order, use the static method ``Sorts.ascending()``,
11- specifying the field on which to sort. To sort in descending (greatest first) order instead,
12- use the static method ``Sorts.descending()``, specifying the field on which to sort. For example,
13- you can sort on ``id`` or ``name`` fields. If you do not specify a sort, MongoDB does not
14- guarantee the order of query results.
7+ .. contents:: On this page
8+ :local:
9+ :backlinks: none
10+ :depth: 2
11+ :class: singlecol
12+
13+ Overview
14+ --------
15+
16+ In this guide, you can learn how to specify the order of your results
17+ from read operations.
18+
19+ Sample Data
20+ ~~~~~~~~~~~
21+
22+ To run the examples in this guide, load these documents into the
23+ ``ratings`` collection of the ``tea`` database with the following
24+ snippet:
25+
26+ .. literalinclude:: /includes/fundamentals/code-snippets/CRUD/sort.go
27+ :language: go
28+ :dedent:
29+ :start-after: begin insertDocs
30+ :end-before: end insertDocs
31+
32+ .. tip:: Non-existent Database and Collections
33+
34+ The driver automatically creates the necessary database and/or collection
35+ when you perform a write operation against them if they don't already exist.
36+
37+ Each document contains a rating for a type of tea, which corresponds to
38+ the ``type`` and ``rating`` fields.
39+
40+ .. note::
41+
42+ Each example truncates the ``ObjectID`` value since the driver
43+ generates them uniquely.
44+
45+ Sort Direction
46+ --------------
47+
48+ To specify the order of your results, pass an interface specifying the
49+ sort fields and directions to the ``SetSort()`` function of a read
50+ operations' options.
51+
52+ The options you specify are the last parameter to the following read
53+ operation functions:
54+
55+ - ``Find()``
56+ - ``FindOne()``
57+ - ``FindOneAndDelete()``
58+ - ``FindOneAndUpdate()``
59+ - ``FindOneAndReplace()``
60+ - ``gridfs.Bucket.Find()``
61+
62+ The sort direction can be **ascending** or **descending**.
63+
64+ Ascending
65+ ~~~~~~~~~
66+
67+ An ascending sort orders your results from smallest to largest. To
68+ specify this sort, pass the field you want to sort by and ``1`` to the
69+ ``SetSort()`` function.
70+
71+ .. tip::
72+
73+ With an ascending sort, the function orders values of type
74+ ``Boolean`` from ``false`` *to* ``true``, ``String`` type values
75+ from *a to z* and numeric type values from *negative infinity to
76+ positive infinity*.
77+
78+ Example
79+ ```````
80+
81+ The following example specifies an ascending sort on the ``rating`` field:
82+
83+ .. literalinclude:: /includes/fundamentals/code-snippets/CRUD/sort.go
84+ :language: go
85+ :dedent:
86+ :start-after: begin ascending sort
87+ :end-before: end ascending sort
88+ :emphasize-lines: 2-3, 5
89+
90+ After running the preceding example, the output resembles the following:
91+
92+ .. code-block:: none
93+ :copyable: false
94+
95+ //results truncated
96+ [{_id ObjectID("...")} {type Assam} {rating 5}]
97+ [{_id ObjectID("...")} {type English Breakfast} {rating 5}]
98+ [{_id ObjectID("...")} {type Oolong} {rating 7}]
99+ [{_id ObjectID("...")} {type Earl Grey} {rating 8}]
100+ [{_id ObjectID("...")} {type Masala} {rating 10}]
101+
102+ Descending
103+ ~~~~~~~~~~
104+
105+ A descending sort orders your results from largest to smallest. To
106+ specify this sort, pass the field you want to sort by and ``-1`` to the
107+ ``SetSort()`` function.
108+
109+ .. tip::
110+
111+ With an descending sort, the function orders values of type
112+ ``Boolean`` from ``true`` *to* ``false``, ``String`` type values
113+ from *z to a* and numeric type values from *positive infinity to
114+ negative infinity*.
115+
116+ Example
117+ ```````
118+
119+ The following example specifies a descending sort on the ``rating`` field:
120+
121+ .. literalinclude:: /includes/fundamentals/code-snippets/CRUD/sort.go
122+ :language: go
123+ :dedent:
124+ :start-after: begin descending sort
125+ :end-before: end descending sort
126+ :emphasize-lines: 2-3, 5
127+
128+ After running the preceding example, the output resembles the following:
129+
130+ .. code-block:: none
131+ :copyable: false
132+
133+ [{_id ObjectID("...")} {type Masala} {rating 10}]
134+ [{_id ObjectID("...")} {type Earl Grey} {rating 8}]
135+ [{_id ObjectID("...")} {type Oolong} {rating 7}]
136+ [{_id ObjectID("...")} {type Assam} {rating 5}]
137+ [{_id ObjectID("...")} {type English Breakfast} {rating 5}]
138+
139+ Handling Ties
140+ ~~~~~~~~~~~~~
141+
142+ A tie occurs when two or more documents have identical values in the
143+ field you are using to sort your results. MongoDB does not guarantee
144+ order if ties occur.
145+
146+ For example, in the sample data, there is a tie for the ``rating`` in
147+ the following documents:
148+
149+ .. code-block:: none
150+ :copyable: false
151+
152+ [{_id ObjectID("...")} {type Assam} {rating 5}]
153+ [{_id ObjectID("...")} {type English Breakfast} {rating 5}]
154+
155+ To guarantee a specific order for documents when ties occur, specify
156+ additional fields to sort by.
157+
158+ Example
159+ ```````
160+
161+ The following example specifies an ascending sort on the ``rating`` field,
162+ then a descending sort on the ``type`` field:
163+
164+ .. literalinclude:: /includes/fundamentals/code-snippets/CRUD/sort.go
165+ :language: go
166+ :dedent:
167+ :start-after: begin multi sort
168+ :end-before: end multi sort
169+ :emphasize-lines: 2-3, 5
170+
171+ After running the preceding example, the output resembles the following:
172+
173+ .. code-block:: none
174+ :copyable: false
175+
176+ [{_id ObjectID("...")} {type English Breakfast} {rating 5}]
177+ [{_id ObjectID("...")} {type Assam} {rating 5}]
178+ [{_id ObjectID("...")} {type Oolong} {rating 7}]
179+ [{_id ObjectID("...")} {type Earl Grey} {rating 8}]
180+ [{_id ObjectID("...")} {type Masala} {rating 10}]
181+
182+ .. tip:: Using Aggregation
183+
184+ You can also specify a sort in an aggregation pipeline by including
185+ the :manual:`$sort </reference/operator/aggregation/sort/>` stage.
186+
187+ The following example specifies the same sort from the preceding
188+ example in an aggregation pipeline:
189+
190+ .. literalinclude:: /includes/fundamentals/code-snippets/CRUD/sort.go
191+ :language: go
192+ :dedent:
193+ :start-after: begin aggregate sort
194+ :end-before: end aggregate sort
195+
196+ Additional Information
197+ ----------------------
198+
199+ For more information on performing read operations, see our guide on
200+ :doc:`retrieving data </fundamentals/crud/read-operations/retrieve>`.
201+
202+ .. For information about sorting text, see our
203+ .. guide on :doc:`Text Search </fundamentals/crud/write-operations/text>`.
204+
205+ API Documentation
206+ ~~~~~~~~~~~~~~~~~
207+
208+ For more information on any of the functions or types discussed in this
209+ guide, see the following API Documentation:
210+
211+ - `Find() <{+api+}/mongo#Collection.Find>`__
212+ - `FindOptions.SetSort() <{+api+}/mongo/options#FindOptions.SetSort>`__
213+ - `Aggregate() <{+api+}/mongo#Collection.Aggregate>`__
214+ - `FindOne() <{+api+}/mongo#Collection.FindOne>`__
215+ - `FindOneAndDelete() <{+api+}/mongo#Collection.FindOneAndDelete>`__
216+ - `FindOneAndUpdate() <{+api+}/mongo#Collection.FindOneAndUpdate>`__
217+ - `FindOneAndReplace() <{+api+}/mongo#Collection.FindOneAndReplace>`__
218+ - `gridfs.Bucket.Find() <{+api+}/mongo/gridfs#Bucket.Find>`__
0 commit comments