Skip to content

Commit e8993f1

Browse files
DOCSP-15336 crud retrieve (#75)
* added CRUD Retrieve page
1 parent 1018d43 commit e8993f1

File tree

3 files changed

+310
-4
lines changed

3 files changed

+310
-4
lines changed

source/fundamentals/crud/read-operations.txt

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,26 +4,26 @@ Read Operations
44

55
.. default-domain:: mongodb
66

7+
- :doc:`/fundamentals/crud/read-operations/retrieve`
78
- :doc:`/fundamentals/crud/read-operations/cursor`
89
- :doc:`/fundamentals/crud/read-operations/sort`
9-
- :doc:`/fundamentals/crud/read-operations/limit`
1010
- :doc:`/fundamentals/crud/read-operations/skip`
11+
- :doc:`/fundamentals/crud/read-operations/limit`
1112

1213
..
13-
- :doc:`/fundamentals/crud/read-operations/retrieve`
1414
- :doc:`/fundamentals/crud/read-operations/project`
1515
- :doc:`/fundamentals/crud/read-operations/geo`
1616
- :doc:`/fundamentals/crud/read-operations/text`
1717

1818
.. toctree::
1919
:caption: Read Operations
2020

21+
/fundamentals/crud/read-operations/retrieve
2122
/fundamentals/crud/read-operations/cursor
2223
/fundamentals/crud/read-operations/sort
23-
/fundamentals/crud/read-operations/limit
2424
/fundamentals/crud/read-operations/skip
25+
/fundamentals/crud/read-operations/limit
2526
..
26-
/fundamentals/crud/read-operations/retrieve
2727
/fundamentals/crud/read-operations/project
2828
/fundamentals/crud/read-operations/geo
2929
/fundamentals/crud/read-operations/text
Lines changed: 206 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,206 @@
1+
==============
2+
Retrieve Data
3+
==============
4+
5+
.. default-domain:: mongodb
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 1
11+
:class: singlecol
12+
13+
Overview
14+
--------
15+
16+
In this guide, you can learn how to retrieve data from your MongoDB
17+
database. To retrieve data, use read operations.
18+
19+
Read operations allow you to do the following:
20+
21+
- Retrieve a subset of documents from your collection using a :ref:`find operation <retrieve-find>`
22+
- Perform transformations on retrieved documents from your collection using an :ref:`aggregate operation <retrieve-aggregate>`
23+
- Monitor real-time changes to your database using a :ref:`change stream <retrieve-watch>`
24+
25+
.. _retrieve-paint-order-collection:
26+
27+
Sample Data for Examples
28+
~~~~~~~~~~~~~~~~~~~~~~~~
29+
30+
The following sections feature examples of how the owner of a paint
31+
store manages their customers' orders. For each order, the owner keeps
32+
track of the color and quantity, which corresponds to the ``color`` and
33+
``qty`` fields in their ``paint_order`` collection:
34+
35+
.. code-block:: json
36+
37+
{ "_id": 1, "color": "purple", "qty": 10 }
38+
{ "_id": 2, "color": "green", "qty": 8 }
39+
{ "_id": 3, "color": "purple", "qty": 4 }
40+
{ "_id": 4, "color": "green", "qty": 11 }
41+
42+
.. _retrieve-find:
43+
44+
Find Operation
45+
--------------
46+
47+
Use the find operation to retrieve a subset of your existing data in
48+
MongoDB. You can specify what data to return including which documents
49+
to retrieve, in what order to retrieve them and how many to retrieve.
50+
51+
To perform a find operation, call the ``find()`` method on an instance
52+
of a ``MongoCollection``. This method searches a collection for documents that
53+
match the query filter you provide. For more information on how to
54+
specify a query, see our :doc:`Specify a Query
55+
</fundamentals/crud/query-document>` guide.
56+
57+
Example
58+
~~~~~~~
59+
60+
The owner would like to know which orders contain greater than three, but
61+
less than nine cans of paint from their :ref:`paint_order collection <retrieve-paint-order-collection>`.
62+
63+
To address this scenario, the owner finds orders to match the criteria:
64+
65+
.. literalinclude:: /includes/fundamentals/code-snippets/Retrieve.java
66+
:language: java
67+
:dedent:
68+
:start-after: begin findExample
69+
:end-before: end findExample
70+
71+
For more information how to build filters, see our :doc:`Filters Builders
72+
</fundamentals/builders/filters>` guide.
73+
74+
The following shows the output of the query specified above:
75+
76+
.. code-block:: json
77+
78+
{ "_id": 2, "color": "green", "qty": 8 }
79+
{ "_id": 3, "color": "purple", "qty": 4 }
80+
81+
After the owner runs this query, they find two orders that matched the
82+
criteria.
83+
84+
For a runnable ``find()`` example, see our :doc:`Find Multiple
85+
Documents </usage-examples/find>` page.
86+
87+
.. _retrieve-aggregate:
88+
89+
Aggregate Operation
90+
-------------------
91+
92+
Use the aggregate operation to perform the stages in an aggregation
93+
pipeline. An aggregation pipeline is a multi-staged transformation that
94+
produces an aggregated result.
95+
96+
To perform an aggregate operation, call the ``aggregate()`` method on an
97+
instance of a ``MongoCollection``. This method accepts aggregation
98+
expressions to run in sequence. To perform aggregations, you can
99+
define aggregation stages that specify how to match documents, rename
100+
fields and group values. For more information, see our
101+
:doc:`Aggregation </fundamentals/aggregation>` guide.
102+
103+
Example
104+
~~~~~~~
105+
106+
The owner would like to know which paint color is the most purchased
107+
(highest quantity sold) from their :ref:`paint_order collection <retrieve-paint-order-collection>`.
108+
109+
To address the scenario, the owner creates an aggregation pipeline that:
110+
111+
- Matches all the documents in the ``paint_order`` collection
112+
- Groups orders by colors
113+
- Sums up the quantity field by color
114+
- Orders the results by highest-to-lowest quantity
115+
116+
.. literalinclude:: /includes/fundamentals/code-snippets/Retrieve.java
117+
:language: java
118+
:dedent:
119+
:start-after: begin aggregateExample
120+
:end-before: end aggregateExample
121+
122+
The following shows the output of the aggregation specified above:
123+
124+
.. code-block:: json
125+
126+
{ "_id": "green", "qty": 19 }
127+
{ "_id": "purple", "qty": 14 }
128+
129+
After the owner runs the aggregation, they find that "green" is the most
130+
purchased color.
131+
132+
For more information on how to construct an aggregation pipeline, see
133+
the MongoDB server manual page on :manual:`Aggregation </aggregation>`.
134+
135+
.. _retrieve-watch:
136+
137+
Change Streams
138+
--------------
139+
140+
Open a change stream to monitor real-time changes to a collection.
141+
Change streams can subscribe to specific types of data changes and
142+
immediately produce change events. For more information on change
143+
streams, see the MongoDB server manual page on :manual:`Change Streams
144+
</changeStreams>`.
145+
146+
To open a change stream, call the ``watch()`` method on an instance of a
147+
``MongoCollection``, ``MongoDatabase`` or ``MongoClient``.
148+
You can pass an aggregation pipeline to this method to notify you as
149+
soon as a change occurs.
150+
151+
.. note::
152+
153+
Change streams don't support standalone MongoDB instances because
154+
they don't have an oplog.
155+
156+
The instance you call the ``watch()`` method on determines the scope of
157+
events which the change stream listens for. If you call ``watch()`` on a
158+
``MongoCollection``, the method monitors a collection. If you call
159+
``watch()`` on a ``MongoDatabase``, the method monitors all the
160+
collections in the database. If you call ``watch()`` on a
161+
``MongoClient``, the method monitors a standalone MongoDB instance, a
162+
replica set, or a sharded cluster.
163+
164+
Example
165+
~~~~~~~
166+
167+
The owner would like to receive notifications for when customers submit new
168+
orders or update their orders from thier :ref:`paint_order collection <retrieve-paint-order-collection>`.
169+
170+
To address this scenario, the owner:
171+
172+
- Creates an aggregation pipeline that filters for "insert" and "update" operation types
173+
- Creates a change stream on the aggregation pipeline
174+
- Prints changes picked up by the change stream
175+
176+
.. literalinclude:: /includes/fundamentals/code-snippets/Retrieve.java
177+
:language: java
178+
:dedent:
179+
:start-after: begin watchExample
180+
:end-before: end watchExample
181+
182+
After creating the change stream, the owner gets notifications for
183+
future inserts or updates to their collection.
184+
185+
An insert notification looks similar to the following:
186+
187+
.. code-block::
188+
189+
Received a change to the collection: ChangeStreamDocument{
190+
operationType=OperationType{value='insert'},
191+
resumeToken={"_data": "825EC..."},
192+
namespace=database.collection,
193+
...
194+
}
195+
196+
For a runnable ``watch()`` example, see our :doc:`Watch For
197+
Changes </usage-examples/watch>` page.
198+
199+
For additional information on the methods mentioned on this page, see
200+
the following API documentation:
201+
202+
- :java-sync-api:`MongoCollection.find() <com/mongodb/client/MongoCollection.html#find()>`
203+
- :java-sync-api:`MongoCollection.aggregate() <com/mongodb/client/MongoCollection.html#aggregate(java.util.List)>`
204+
- :java-sync-api:`MongoCollection.watch() <com/mongodb/client/MongoCollection.html#watch()>`
205+
- :java-sync-api:`MongoDatabase.watch() <com/mongodb/client/MongoDatabase.html#watch()>`
206+
- :java-sync-api:`MongoClient.watch() <com/mongodb/client/MongoClient.html#watch()>`
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
package docs;
2+
3+
import com.mongodb.client.ChangeStreamIterable;
4+
import com.mongodb.client.MongoClient;
5+
import com.mongodb.client.MongoClients;
6+
import com.mongodb.client.MongoCollection;
7+
import com.mongodb.client.MongoDatabase;
8+
9+
import org.bson.Document;
10+
import org.bson.conversions.Bson;
11+
12+
import java.util.ArrayList;
13+
import java.util.Arrays;
14+
import java.util.List;
15+
16+
import com.mongodb.client.model.Filters;
17+
import com.mongodb.client.model.Sorts;
18+
import com.mongodb.client.model.Aggregates;
19+
import com.mongodb.client.model.Accumulators;
20+
import com.mongodb.client.model.changestream.FullDocument;
21+
22+
public class Retrieve {
23+
24+
private final MongoCollection<Document> collection;
25+
private final MongoClient mongoClient;
26+
private final MongoDatabase database;
27+
28+
private Retrieve() {
29+
final String uri = System.getenv("DRIVER_REF_URI");
30+
31+
mongoClient = MongoClients.create(uri);
32+
database = mongoClient.getDatabase("crudOps");
33+
collection = database.getCollection("retrieve");
34+
}
35+
36+
public static void main(String [] args){
37+
Retrieve retrieve = new Retrieve();
38+
retrieve.preview(true);
39+
retrieve.setupPaintOrderCollection();
40+
41+
System.out.println("Find Example: ");
42+
retrieve.findExample();
43+
44+
System.out.println("Aggregate Example: ");
45+
retrieve.aggregateExample();
46+
47+
System.out.println("Watch Example: ");
48+
retrieve.watchExample();
49+
retrieve.setupPaintOrderCollection();
50+
51+
}
52+
53+
private void findExample(){
54+
// begin findExample
55+
Bson filter = Filters.and(Filters.gt("qty", 3), Filters.lt("qty", 9));
56+
collection.find(filter).forEach(doc -> System.out.println(doc.toJson()));
57+
// end findExample
58+
}
59+
60+
private void aggregateExample(){
61+
// begin aggregateExample
62+
Bson filter = Filters.empty();
63+
collection.aggregate(Arrays.asList(
64+
Aggregates.match(filter),
65+
Aggregates.group("$color", Accumulators.sum("qty", "$qty")),
66+
Aggregates.sort(Sorts.descending("qty"))))
67+
.forEach(doc -> System.out.println(doc.toJson()));
68+
// end aggregateExample
69+
}
70+
71+
private void watchExample(){
72+
// begin watchExample
73+
List<Bson> pipeline = Arrays.asList(
74+
Aggregates.match(Filters.in("operationType", Arrays.asList("insert", "update"))));
75+
76+
ChangeStreamIterable<Document> changeStream = database.watch(pipeline)
77+
.fullDocument(FullDocument.UPDATE_LOOKUP);
78+
79+
changeStream.forEach(event ->
80+
System.out.println("Received a change to the collection: " + event));
81+
// end watchExample
82+
}
83+
84+
private void preview(boolean drop){
85+
Bson filter = Filters.empty();
86+
collection.find(filter).forEach(doc -> System.out.println(doc.toJson()));
87+
if (drop){
88+
collection.drop();
89+
}
90+
}
91+
92+
private void setupPaintOrderCollection() {
93+
collection.insertMany(Arrays.asList(
94+
new Document("_id", 1).append("color", "purple").append("qty", 10),
95+
new Document("_id", 2).append("color", "green").append("qty", 8),
96+
new Document("_id", 3).append("color", "purple").append("qty", 4),
97+
new Document("_id", 4).append("color", "green").append("qty", 11)
98+
));
99+
}
100+
}

0 commit comments

Comments
 (0)