Skip to content

Commit 5cf1226

Browse files
authored
Merge pull request #45 from ksadoff/DOCSP-9557
DOCSP-9557: Fundamentals > CRUD Operations > Read Operations > Sort Results
2 parents 9d5b3e3 + 960a4dd commit 5cf1226

File tree

1 file changed

+138
-0
lines changed

1 file changed

+138
-0
lines changed

source/fundamentals/crud/sort.txt

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
============
2+
Sort Results
3+
============
4+
5+
.. default-domain:: mongodb
6+
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.
15+
16+
Follow the instructions in the examples below to insert data into
17+
a collection and perform a sort on the results of a query.
18+
Consider a collection containing documents that describe books. To
19+
insert this data into a collection, run the following operation:
20+
21+
.. code-block:: java
22+
23+
collection.insertMany(Arrays.asList(
24+
new Document().append("_id", 1)
25+
.append("title", "The Brothers Karamazov").append("length", 824)
26+
.append("author", "Dostoyevsky"),
27+
new Document().append("_id", 2)
28+
.append("title", "Les Misérables").append("length", 1462).append("author", "Hugo"),
29+
new Document().append("_id", 3)
30+
.append("title", "Atlas Shrugged").append("length", 1088).append("author", "Rand"),
31+
new Document().append("_id", 4)
32+
.append("title", "Infinite Jest").append("length", 1104).append("author", "Wallace"),
33+
new Document().append("_id", 5)
34+
.append("title", "Cryptonomicon").append("length", 918).append("author", "Stephenson"),
35+
new Document().append("_id", 6)
36+
.append("title", "A Dance with Dragons").append("length", 1104)
37+
.append("author", "Martin")
38+
));
39+
40+
Call the ``sort()`` function and specify the order with ``ascending()`` to ensure that the
41+
operation returns books in alphabetical order by title:
42+
43+
.. code-block:: java
44+
:emphasize-lines: 5
45+
46+
import static com.mongodb.client.model.Sorts.ascending;
47+
48+
// define a cursor that can iterate through the results of the query
49+
MongoCursor<Document> cursor = collection.find()
50+
.sort(ascending("title")).iterator();
51+
// print out items in alphabetical order
52+
try {
53+
while (cursor.hasNext()) {
54+
System.out.println(cursor.next());
55+
}
56+
// close the cursor
57+
} finally {
58+
cursor.close();
59+
}
60+
61+
This sample code prints the documents in ascending order on the ``title`` field as follows:
62+
63+
.. code-block:: java
64+
65+
Document{{_id=6, title=A Dance with Dragons, length=1104, author=Martin}}
66+
Document{{_id=3, title=Atlas Shrugged, length=1088, author=Rand}}
67+
Document{{_id=5, title=Cryptonomicon, length=918, author=Stephenson}}
68+
Document{{_id=4, title=Infinite Jest, length=1104, author=Wallace}}
69+
Document{{_id=2, title=Les Misérables, length=1462, author=Hugo}}
70+
Document{{_id=1, title=The Brothers Karamazov, length=824, author=Dostoyevsky}}
71+
72+
Sometimes, the order of two or more documents is ambiguous using a
73+
specified sort. Consider the case of sorting by length: in the above case,
74+
both "A Dance with Dragons" and "Infinite Jest" have ``1104`` pages, so
75+
the order in which ``sort()`` returns them is not guaranteed. To resolve ties in
76+
your sorted results in a repeatable way, add additional fields to the
77+
``Sorts.ascending()`` function call.
78+
Call the ``sort()`` method, specifying ``length`` as
79+
the first field by which to sort and the ``title`` field as the second field. In the event
80+
that the ``length`` field comparison results in a tie, the operation compares the tied results
81+
using the ``title`` field:
82+
83+
84+
.. code-block:: java
85+
:emphasize-lines: 3
86+
87+
// sort first by length, then title
88+
MongoCursor<Document> cursor = collection.find()
89+
.sort(ascending("length", "title")).iterator();
90+
91+
This sample code prints your query results in ascending order by length.
92+
When there are two documents with the same ``length`` value, it resolves the tie using the
93+
``title`` field you specified as the second parameter.
94+
95+
.. code-block:: java
96+
97+
Document{{_id=1, title=The Brothers Karamazov, length=824, author=Dostoyevsky}}
98+
Document{{_id=5, title=Cryptonomicon, length=918, author=Stephenson}}
99+
Document{{_id=3, title=Atlas Shrugged, length=1088, author=Rand}}
100+
Document{{_id=6, title=A Dance with Dragons, length=1104, author=Martin}}
101+
Document{{_id=4, title=Infinite Jest, length=1104, author=Wallace}}
102+
Document{{_id=2, title=Les Misérables, length=1462, author=Hugo}}
103+
104+
You can also sort by multiple fields in different orders, using ``Sorts.orderBy()``.
105+
Consider this example where you first sort on ``length`` in an ascending order, and then on
106+
``title`` in a descending order:
107+
108+
.. code-block:: java
109+
:emphasize-lines: 7
110+
111+
import static com.mongodb.client.model.Sorts.ascending;
112+
import static com.mongodb.client.model.Sorts.descending;
113+
import static com.mongodb.client.model.Sorts.orderBy;
114+
115+
// sort first by length ascending, then title descending
116+
MongoCursor<Document> cursor = collection.find()
117+
.sort(orderBy(ascending("length"), descending("title")))
118+
.iterator();
119+
120+
In the returned documents, notice how the two books with the same
121+
length - "Infinite Jest" and "A Dance with Dragons" -
122+
appear in the reverse of the order shown in the previous example:
123+
124+
.. code-block:: java
125+
126+
Document{{_id=1, title=The Brothers Karamazov, length=824, author=Dostoyevksy}}
127+
Document{{_id=5, title=Cryptonomicon, length=918, author=Stephenson}}
128+
Document{{_id=3, title=Atlas Shrugged, length=1088, author=Rand}}
129+
Document{{_id=4, title=Infinite Jest, length=1104, author=Wallace}}
130+
Document{{_id=6, title=A Dance with Dragons, length=1104, author=Martin}}
131+
Document{{_id=2, title=Les Misérables, length=1462, author=Hugo}}
132+
133+
For additional information on the classes and methods mentioned on this
134+
page, see the following API documentation:
135+
136+
- :java-sync-api:`FindIterable <com/mongodb/client/FindIterable.html>`
137+
- :java-sync-api:`MongoCursor <com/mongodb/client/MongoCursor.html>`
138+
- :java-docs:`Sorts </apidocs/mongodb-driver-core/com/mongodb/client/model/Sorts.html>`

0 commit comments

Comments
 (0)