Skip to content

Commit 17f8032

Browse files
DOCSP-9561 crud cursor (#72)
* added CRUD Cursor page
1 parent 5e0d358 commit 17f8032

File tree

2 files changed

+278
-1
lines changed

2 files changed

+278
-1
lines changed

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

Lines changed: 155 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,158 @@ Access Data From a Cursor
55
.. default-domain:: mongodb
66

77
Read operations that return multiple documents do not immediately return
8-
all values matching the query.
8+
all values matching the query. Because a query can potentially match
9+
large number of documents, we need to be able to access or store the
10+
matched documents.
11+
12+
This page uses an initiating method, ``find()`` to show how to access
13+
data from a :java-docs:`FindIterable
14+
<apidocs/mongodb-driver-sync/com/mongodb/client/FindIterable.html>` .
15+
16+
.. note::
17+
18+
The ways to access and store data mentioned below applies equally to
19+
other iterables such as an :java-docs:`AggregateIterable
20+
<apidocs/mongodb-driver-sync/com/mongodb/client/AggregateIterable.html>`.
21+
22+
The ``find()`` method iterates through all the documents in your
23+
collection to find documents that match your query and returns an
24+
instance of a ``FindIterable``.
25+
26+
A ``FindIterable`` consists of documents matched by your search criteria
27+
and allows you to further specify which documents to see by setting
28+
paramaters though methods.
29+
30+
Terminal Methods
31+
----------------
32+
33+
Terminal methods execute an operation on the MongoDB server after
34+
configuring all parameters of an ``Iterable`` instance controlling the
35+
operation.
36+
37+
First
38+
~~~~~
39+
40+
Use the :java-docs:`first() <apidocs/mongodb-driver-sync/com/mongodb/client/MongoIterable.html#first()>`
41+
method to retireve the first document in your query results:
42+
43+
.. literalinclude:: /includes/fundamentals/code-snippets/Cursor.java
44+
:language: java
45+
:dedent:
46+
:start-after: begin firstExample
47+
:end-before: end firstExample
48+
49+
This method is often used when your query filter will match one
50+
document, such as when filtering by a unique index.
51+
52+
Into
53+
~~~~
54+
55+
Use the :java-docs:`into() <apidocs/mongodb-driver-sync/com/mongodb/client/MongoIterable.html#into(A)>`
56+
method to store your query results in a ``List``:
57+
58+
.. literalinclude:: /includes/fundamentals/code-snippets/Cursor.java
59+
:language: java
60+
:dedent:
61+
:start-after: begin intoExample
62+
:end-before: end intoExample
63+
64+
This method is often used when your query filter returns a small number
65+
of documents that can fit into available memory.
66+
67+
Cursor
68+
~~~~~~
69+
70+
Use the :java-docs:`cursor() <apidocs/mongodb-driver-sync/com/mongodb/client/MongoIterable.html#cursor()>`
71+
method to iterate through fetched documents and ensure that the cursor
72+
closes if there is an early termination:
73+
74+
.. code-block:: java
75+
:copyable: true
76+
77+
MongoCursor<Document> cursor = collection.find().cursor();
78+
79+
For more information on how to ensure a cursor closes, see the :ref:`cursor cleanup section <cursor_cleanup>`.
80+
81+
Usage Patterns
82+
--------------
83+
84+
A ``MongoCursor`` and ``FindIterable`` allow you to access query results
85+
one document at a time, abstracting away network and caching logic.
86+
87+
Functional Iteration
88+
~~~~~~~~~~~~~~~~~~~~~
89+
90+
Pass a function to the
91+
`forEach() <https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Iterable.html?is-external=true#forEach(java.util.function.Consumer)>`_
92+
method of a ``FindIterable`` to iterate through results in a functional style:
93+
94+
.. literalinclude:: /includes/fundamentals/code-snippets/Cursor.java
95+
:language: java
96+
:dedent:
97+
:start-after: begin forEachIteration
98+
:end-before: end forEachIteration
99+
100+
.. warning::
101+
102+
Initiating methods implement the Iterable interface which allows you
103+
to iterate using iterator methods. Sometimes, we use an enhanced
104+
for-each loop to iterate through results:
105+
106+
.. code-block:: java
107+
108+
for (Document cur : collection.find()) {
109+
...
110+
}
111+
112+
Iterating this way is not preferable because if an exception is
113+
thrown before the loop completes, the cursor will not close. Using a
114+
``MongoCursor`` allows us to ensure the cursor closes as shown in the
115+
:ref:`cursor cleanup section <cursor_cleanup>`.
116+
117+
Conditional Iteration
118+
~~~~~~~~~~~~~~~~~~~~~
119+
120+
Use the :java-docs:`hasNext() <apidocs/mongodb-driver-sync/com/mongodb/client/MongoCursor.html#hasNext()>`
121+
method to check if there are any documents available in the cursor, and then use the
122+
:java-docs:`next() <apidocs/mongodb-driver-sync/com/mongodb/client/MongoCursor.html#next()>`
123+
method to retrieve the next available document from the cursor:
124+
125+
.. literalinclude:: /includes/fundamentals/code-snippets/Cursor.java
126+
:language: java
127+
:dedent:
128+
:start-after: begin manualIteration
129+
:end-before: end manualIteration
130+
131+
.. _cursor_cleanup:
132+
133+
Cursor Cleanup
134+
--------------
135+
136+
Close
137+
~~~~~
138+
139+
Use the
140+
:java-docs:`close() <apidocs/mongodb-driver-sync/com/mongodb/client/MongoCursor.html#close()>`
141+
method in a finally block to free up a cursor's consumption of resources
142+
in both the client application and the MongoDB server:
143+
144+
.. literalinclude:: /includes/fundamentals/code-snippets/Cursor.java
145+
:language: java
146+
:dedent:
147+
:start-after: begin closeExample
148+
:end-before: end closeExample
149+
150+
Try with Resources Statement
151+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
152+
153+
Use a `try-with-resources statement
154+
<https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html>`_
155+
to automatically free up a cursor's consumption of resources in both the
156+
client application and the MongoDB server:
157+
158+
.. literalinclude:: /includes/fundamentals/code-snippets/Cursor.java
159+
:language: java
160+
:dedent:
161+
:start-after: begin tryWithResourcesExample
162+
:end-before: end tryWithResourcesExample
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
package docs;
2+
3+
import com.mongodb.client.MongoClient;
4+
import com.mongodb.client.MongoClients;
5+
import com.mongodb.client.MongoCollection;
6+
import com.mongodb.client.MongoDatabase;
7+
import com.mongodb.client.*;
8+
9+
import org.bson.conversions.Bson;
10+
11+
import java.util.Arrays;
12+
import java.util.List;
13+
import java.util.ArrayList;
14+
15+
import org.bson.Document;
16+
import com.mongodb.client.model.Filters;
17+
18+
public class Cursor {
19+
private final MongoClient mongoClient;
20+
private final MongoDatabase database;
21+
private MongoCollection<Document> collection;
22+
23+
private Cursor(){
24+
final String uri = System.getenv("DRIVER_REF_URI");
25+
26+
mongoClient = MongoClients.create(uri);
27+
database = mongoClient.getDatabase("test");
28+
collection = database.getCollection("orders");
29+
}
30+
31+
public static void main(String [] args){
32+
Cursor c = new Cursor();
33+
c.setupPaintCollection();
34+
35+
System.out.println("For Each Iteration");
36+
c.forEachIteration();
37+
38+
System.out.println("First Example");
39+
c.firstExample();
40+
41+
System.out.println("Into Example");
42+
c.intoExample();
43+
44+
System.out.println("Manual Iteration");
45+
c.manualIteration();
46+
47+
System.out.println("Close Example");
48+
c.closeExample();
49+
50+
System.out.println("Try With Resources");
51+
c.tryWithResourcesExample();
52+
}
53+
54+
private void forEachIteration(){
55+
// begin forEachIteration
56+
FindIterable<Document> iterable = collection.find();
57+
iterable.forEach(doc -> System.out.println(doc.toJson()));
58+
// end forEachIteration
59+
}
60+
61+
private void firstExample(){
62+
// begin firstExample
63+
FindIterable<Document> iterable = collection.find();
64+
System.out.println(iterable.first());
65+
// end firstExample
66+
}
67+
68+
private void intoExample(){
69+
// begin intoExample
70+
List<Document> results = new ArrayList<>();
71+
FindIterable<Document> iterable = collection.find();
72+
iterable.into(results);
73+
System.out.println(results);
74+
// end intoExample
75+
}
76+
77+
private void manualIteration(){
78+
// begin manualIteration
79+
MongoCursor<Document> cursor = collection.find().cursor();
80+
while (cursor.hasNext()){
81+
System.out.println(cursor.next().toJson());
82+
}
83+
// end manualIteration
84+
}
85+
86+
private void closeExample(){
87+
// begin closeExample
88+
MongoCursor<Document> cursor = collection.find().cursor();
89+
90+
try {
91+
while (cursor.hasNext()){
92+
System.out.println(cursor.next().toJson());
93+
}
94+
} finally {
95+
cursor.close();
96+
}
97+
// end closeExample
98+
}
99+
100+
private void tryWithResourcesExample(){
101+
// begin tryWithResourcesExample
102+
try(MongoCursor<Document> cursor = collection.find().cursor()) {
103+
while (cursor.hasNext()){
104+
System.out.println(cursor.next().toJson());
105+
}
106+
}
107+
// end tryWithResourcesExample
108+
}
109+
110+
public void setupPaintCollection(){
111+
collection.drop();
112+
collection.insertMany(Arrays.asList(
113+
new Document("_id", 1).append("color", "red").append("qty", 5),
114+
new Document("_id", 2).append("color", "purple").append("qty", 10),
115+
new Document("_id", 3).append("color", "blue").append("qty", 9),
116+
new Document("_id", 4).append("color", "white").append("qty", 6),
117+
new Document("_id", 5).append("color", "yellow").append("qty", 11),
118+
new Document("_id", 6).append("color", "pink").append("qty", 3),
119+
new Document("_id", 7).append("color", "green").append("qty", 8),
120+
new Document("_id", 8).append("color", "orange").append("qty", 7)
121+
));
122+
}
123+
}

0 commit comments

Comments
 (0)