-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathsort.txt
289 lines (211 loc) · 7.72 KB
/
sort.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
.. _golang-sort-results:
============
Sort Results
============
.. meta::
:description: Learn how to sort query results, handle ties, and apply sorting in aggregation pipelines with the MongoDB Go Driver.
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol
Overview
--------
In this guide, you can learn how to specify the order of your results
from an operation.
Sample Data
~~~~~~~~~~~
The examples in this guide use the following ``Course`` struct as a model for documents
in the ``courses`` collection:
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/sort.go
:start-after: start-course-struct
:end-before: end-course-struct
:language: go
:dedent:
To run the examples in this guide, load the sample data into the
``db.courses`` collection with the following snippet:
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/sort.go
:language: go
:dedent:
:start-after: begin insertDocs
:end-before: end insertDocs
.. include:: /includes/fundamentals/automatic-db-coll-creation.rst
Each document contains a description of a university course that
includes the course title and maximum enrollment, corresponding to
the ``title`` and ``enrollment`` fields in each document.
Sort Direction
--------------
To specify the order of your results, pass an interface specifying the
sort fields and direction to the ``SetSort()`` method of an operation's options.
The following operations take options as a parameter:
- ``Find()``
- ``FindOne()``
- ``FindOneAndDelete()``
- ``FindOneAndUpdate()``
- ``FindOneAndReplace()``
- ``GridFSBucket.Find()``
You can set an **ascending** or **descending** sort direction.
Ascending
~~~~~~~~~
An ascending sort orders your results from smallest to largest. To
specify this sort, pass the field you want to sort by and ``1`` to the
``SetSort()`` method.
.. tip::
With an ascending sort, the method orders values of type
``Boolean`` from ``false`` *to* ``true``, ``String`` type values
from *a to z* and numeric type values from *negative infinity to
positive infinity*.
Example
```````
The following example specifies an ascending sort on the ``enrollment`` field:
.. io-code-block::
:copyable: true
.. input::
:language: go
filter := bson.D{}
opts := options.Find().SetSort(bson.D{{"enrollment", 1}})
cursor, err := coll.Find(context.TODO(), filter, opts)
var results []Course
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
res, _ := bson.MarshalExtJSON(result, false, false)
fmt.Println(string(res))
}
.. output::
:language: none
:visible: false
{"title":"Modern Poetry","enrollment":12}
{"title":"World Fiction","enrollment":35}
{"title":"Plate Tectonics","enrollment":35}
{"title":"Abstract Algebra","enrollment":60}
Descending
~~~~~~~~~~
A descending sort orders your results from largest to smallest. To
specify this sort, pass the field you want to sort by and ``-1`` to the
``SetSort()`` method.
.. tip::
With an descending sort, the method orders values of type
``Boolean`` from ``true`` *to* ``false``, ``String`` type values
from *z to a* and numeric type values from *positive infinity to
negative infinity*.
Example
```````
The following example specifies a descending sort on the ``enrollment`` field:
.. io-code-block::
:copyable: true
.. input::
:language: go
filter := bson.D{}
opts := options.Find().SetSort(bson.D{{"enrollment", -1}})
cursor, err := coll.Find(context.TODO(), filter, opts)
var results []Course
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
res, _ := bson.MarshalExtJSON(result, false, false)
fmt.Println(string(res))
}
.. output::
:language: none
:visible: false
{"title":"Abstract Algebra","enrollment":60}
{"title":"World Fiction","enrollment":35}
{"title":"Plate Tectonics","enrollment":35}
{"title":"Modern Poetry","enrollment":12}
Handling Ties
~~~~~~~~~~~~~
A tie occurs when two or more documents have identical values in the
field you are using to sort your results. MongoDB does not guarantee
order if ties occur.
For example, in the sample data, there is a tie for ``enrollment`` in
the following documents:
.. code-block:: none
:copyable: false
{"title":"World Fiction","enrollment":35}
{"title":"Plate Tectonics","enrollment":35}
You can sort on additional fields to resolve ties in the original sort.
If you want to guarantee a specific order for documents, select sort fields
that do not result in ties.
Example
```````
The following example specifies a descending sort on the ``enrollment`` field,
then an ascending sort on the ``title`` field:
.. io-code-block::
:copyable: true
.. input::
:language: go
filter := bson.D{}
opts := options.Find().SetSort(bson.D{{"enrollment", -1}, {"title", 1}})
cursor, err := coll.Find(context.TODO(), filter, opts)
var results []Course
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
res, _ := bson.MarshalExtJSON(result, false, false)
fmt.Println(string(res))
}
.. output::
:language: none
:visible: false
{"title":"Abstract Algebra","enrollment":60}
{"title":"Plate Tectonics","enrollment":35}
{"title":"World Fiction","enrollment":35}
{"title":"Modern Poetry","enrollment":12}
Aggregation
~~~~~~~~~~~
You can also include the :manual:`$sort </reference/operator/aggregation/sort/>`
stage to specify a sort in an aggregation pipeline.
Example
```````
The following example specifies a descending sort on the ``enrollment``
field, then an ascending sort on the ``title`` field:
.. io-code-block::
:copyable: true
.. input::
:language: go
sortStage := bson.D{{"$sort", bson.D{{"enrollment", -1}, {"title", 1}}}}
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{sortStage})
if err != nil {
panic(err)
}
var results []Course
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
res, _ := bson.MarshalExtJSON(result, false, false)
fmt.Println(string(res))
}
.. output::
:language: none
:visible: false
{"title":"Abstract Algebra","enrollment":60}
{"title":"Plate Tectonics","enrollment":35}
{"title":"World Fiction","enrollment":35}
{"title":"Modern Poetry","enrollment":12}
Additional Information
----------------------
To learn more about the operations mentioned, see the following
guides:
- :ref:`golang-query-document`
- :ref:`golang-retrieve`
- :ref:`golang-compound-operations`
- :ref:`golang-aggregation`
To learn about sorting text scores from your text search, see :ref:`golang-search-text`.
API Documentation
~~~~~~~~~~~~~~~~~
To learn more about any of the methods or types discussed in this
guide, see the following API Documentation:
- `Find() <{+api+}/mongo#Collection.Find>`__
- `FindOptionsBuilder.SetSort() <{+api+}/mongo/options#FindOptionsBuilder.SetSort>`__
- `Aggregate() <{+api+}/mongo#Collection.Aggregate>`__
- `FindOne() <{+api+}/mongo#Collection.FindOne>`__
- `FindOneAndDelete() <{+api+}/mongo#Collection.FindOneAndDelete>`__
- `FindOneAndUpdate() <{+api+}/mongo#Collection.FindOneAndUpdate>`__
- `FindOneAndReplace() <{+api+}/mongo#Collection.FindOneAndReplace>`__
- `GridFSBucket.Find() <{+api+}/mongo#GridFSBucket.Find>`__