Skip to content

Commit 8eac273

Browse files
DOCSP-13835 crud sort (#60)
* added CRUD Sort page
1 parent 70a6d18 commit 8eac273

File tree

4 files changed

+333
-12
lines changed

4 files changed

+333
-12
lines changed

source/fundamentals/crud/read-operations.txt

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@ Read Operations
55
.. default-domain:: mongodb
66

77
- :doc:`/fundamentals/crud/read-operations/retrieve`
8+
- :doc:`/fundamentals/crud/read-operations/sort`
89

910
..
1011
- :doc:`/fundamentals/crud/read-operations/cursor`
11-
- :doc:`/fundamentals/crud/read-operations/sort`
1212
- :doc:`/fundamentals/crud/read-operations/limit`
1313
- :doc:`/fundamentals/crud/read-operations/skip`
1414
- :doc:`/fundamentals/crud/read-operations/project`
@@ -19,12 +19,11 @@ Read Operations
1919
:caption: Read Operations
2020

2121
/fundamentals/crud/read-operations/retrieve
22+
/fundamentals/crud/read-operations/sort
2223
..
2324
/fundamentals/crud/read-operations/cursor
24-
/fundamentals/crud/read-operations/sort
2525
/fundamentals/crud/read-operations/limit
2626
/fundamentals/crud/read-operations/skip
2727
/fundamentals/crud/read-operations/project
2828
/fundamentals/crud/read-operations/geo
2929
/fundamentals/crud/read-operations/text
30-

source/fundamentals/crud/read-operations/retrieve.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ the MongoDB server manual page on :manual:`Aggregation
144144
Additional Information
145145
----------------------
146146

147-
For runnable examples of the update operations, see the following usage
147+
For runnable examples of the find operations, see the following usage
148148
examples:
149149

150150
- :doc:`Find a Document </usage-examples/findOne>`

source/fundamentals/crud/read-operations/sort.txt

Lines changed: 212 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -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>`__
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"log"
7+
"os"
8+
9+
"go.mongodb.org/mongo-driver/bson"
10+
"go.mongodb.org/mongo-driver/mongo"
11+
"go.mongodb.org/mongo-driver/mongo/options"
12+
)
13+
14+
func main() {
15+
var uri string
16+
if uri = os.Getenv("MONGODB_URI"); uri == "" {
17+
log.Fatal("You must set your 'MONGODB_URI' environmental variable. See\n\t https://docs.mongodb.com/drivers/go/current/usage-examples/")
18+
}
19+
20+
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
21+
22+
if err != nil {
23+
panic(err)
24+
}
25+
defer func() {
26+
if err = client.Disconnect(context.TODO()); err != nil {
27+
panic(err)
28+
}
29+
}()
30+
31+
client.Database("tea").Collection("ratings").Drop(context.TODO())
32+
33+
// begin insertDocs
34+
coll := client.Database("tea").Collection("ratings")
35+
docs := []interface{}{
36+
bson.D{{"type", "Masala"}, {"rating", 10}},
37+
bson.D{{"type", "Assam"}, {"rating", 5}},
38+
bson.D{{"type", "Oolong"}, {"rating", 7}},
39+
bson.D{{"type", "Earl Grey"}, {"rating", 8}},
40+
bson.D{{"type", "English Breakfast"}, {"rating", 5}},
41+
}
42+
43+
result, insertErr := coll.InsertMany(context.TODO(), docs)
44+
if insertErr != nil {
45+
panic(insertErr)
46+
}
47+
//end insertDocs
48+
fmt.Printf("Number of documents inserted: %d\n", len(result.InsertedIDs))
49+
50+
fmt.Println("Ascending Sort:")
51+
//begin ascending sort
52+
ascendingFilter := bson.D{}
53+
acendingSort := bson.D{{"rating", 1}}
54+
ascendingOptions := options.Find().SetSort(acendingSort)
55+
56+
ascendingCursor, ascendingErr := coll.Find(context.TODO(), ascendingFilter, ascendingOptions)
57+
58+
var ascendingResults []bson.D
59+
if ascendingErr = ascendingCursor.All(context.TODO(), &ascendingResults); ascendingErr != nil {
60+
panic(ascendingErr)
61+
}
62+
for _, result := range ascendingResults {
63+
fmt.Println(result)
64+
}
65+
//end ascending sort
66+
67+
fmt.Println("Descending Sort:")
68+
//begin descending sort
69+
descendingFilter := bson.D{}
70+
descendingSort := bson.D{{"rating", -1}}
71+
descendingOptions := options.Find().SetSort(descendingSort)
72+
73+
descendingCursor, descendingErr := coll.Find(context.TODO(), descendingFilter, descendingOptions)
74+
75+
var descendingResults []bson.D
76+
if descendingErr = descendingCursor.All(context.TODO(), &descendingResults); descendingErr != nil {
77+
panic(descendingErr)
78+
}
79+
for _, result := range descendingResults {
80+
fmt.Println(result)
81+
}
82+
//end descending sort
83+
84+
fmt.Println("Multi Sort:")
85+
//begin multi sort
86+
findFilter := bson.D{}
87+
sort := bson.D{{"rating", 1}, {"type", -1}}
88+
findOptions := options.Find().SetSort(sort)
89+
90+
findCursor, findErr := coll.Find(context.TODO(), findFilter, findOptions)
91+
92+
var findResults []bson.D
93+
if findErr = findCursor.All(context.TODO(), &findResults); findErr != nil {
94+
panic(findErr)
95+
}
96+
for _, result := range findResults {
97+
fmt.Println(result)
98+
}
99+
//end multi sort
100+
101+
fmt.Println("Aggregation Sort:")
102+
// begin aggregate sort
103+
sortStage := bson.D{{"$sort", bson.D{{"rating", 1}, {"type", -1}}}}
104+
105+
aggCursor, aggErr := coll.Aggregate(context.TODO(), mongo.Pipeline{sortStage})
106+
if aggErr != nil {
107+
panic(aggErr)
108+
}
109+
110+
var aggResults []bson.D
111+
if aggErr = aggCursor.All(context.TODO(), &aggResults); aggErr != nil {
112+
panic(aggErr)
113+
}
114+
for _, result := range aggResults {
115+
fmt.Println(result)
116+
}
117+
// end aggregate sort
118+
}

0 commit comments

Comments
 (0)