Skip to content

Commit dece97e

Browse files
committed
aggregation and modify
1 parent ef754bf commit dece97e

File tree

7 files changed

+508
-263
lines changed

7 files changed

+508
-263
lines changed

config/redirects

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,10 @@ raw: ${prefix}/master -> ${base}/upcoming/
2525
[v5.3-master]: ${prefix}/${version}/fundamentals/crud/read-operations/project/ -> ${base}/${version}/crud/query-documents/project/
2626
[v5.3-master]: ${prefix}/${version}/fundamentals/crud/read-operations/geo/ -> ${base}/${version}/crud/query-documents/geo/
2727
[v5.3-master]: ${prefix}/${version}/fundamentals/crud/read-operations/text/ -> ${base}/${version}/crud/query-documents/text/
28-
[v5.3-master]: ${prefix}/${version}/fundamentals/crud/write-operations/ -> ${base}/${version}/crud/update-documents/
29-
[v5.3-master]: ${prefix}/${version}/fundamentals/crud/write-operations/insert/ -> ${base}/${version}/crud/update-documents/insert/
28+
[v5.3-master]: ${prefix}/${version}/fundamentals/crud/write-operations/ -> ${base}/${version}/crud/insert/
29+
[v5.3-master]: ${prefix}/${version}/fundamentals/crud/write-operations/insert/ -> ${base}/${version}/crud/insert/
3030
[v5.3-master]: ${prefix}/${version}/fundamentals/crud/write-operations/delete/ -> ${base}/${version}/crud/update-documents/delete/
31-
[v5.3-master]: ${prefix}/${version}/fundamentals/crud/write-operations/modify/ -> ${base}/${version}/crud/update-documents/modify/
31+
[v5.3-master]: ${prefix}/${version}/fundamentals/crud/write-operations/modify/ -> ${base}/${version}/crud/update-documents/
3232
[v5.3-master]: ${prefix}/${version}/fundamentals/crud/write-operations/embedded-arrays/ -> ${base}/${version}/crud/update-documents/embedded-arrays/
3333
[v5.3-master]: ${prefix}/${version}/fundamentals/crud/write-operations/upsert/ -> ${base}/${version}/crud/update-documents/upsert/
3434
[v5.3-master]: ${prefix}/${version}/fundamentals/crud/write-operations/bulk/ -> ${base}/${version}/crud/bulk/

source/aggregation.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ Aggregation
2121
:caption: Aggregation
2222

2323
Aggregation Expressions </aggregation/aggregation-expression-operations>
24+
Aggregation Examples </aggregation/aggregation-examples>
2425

2526
Overview
2627
--------
Lines changed: 230 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
1+
.. _java-aggregation-examples:
2+
3+
====================
4+
Aggregation Examples
5+
====================
6+
7+
.. facet::
8+
:name: genre
9+
:values: reference
10+
11+
.. meta::
12+
:keywords: code example, transform, computed
13+
14+
.. contents:: On this page
15+
:local:
16+
:backlinks: none
17+
:depth: 2
18+
:class: singlecol
19+
20+
Overview
21+
--------
22+
23+
This page demonstrates how to use aggregation pipelines.
24+
25+
Import Classes
26+
~~~~~~~~~~~~~~
27+
28+
Create a new Java file called ``AggTour.java`` and include the following import statements:
29+
30+
.. literalinclude:: /includes/fundamentals/code-snippets/AggTour.java
31+
:language: java
32+
:dedent:
33+
:start-after: begin imports
34+
:end-before: end imports
35+
36+
Connect to a MongoDB Deployment
37+
+++++++++++++++++++++++++++++++
38+
39+
.. code-block:: java
40+
41+
public class AggTour {
42+
43+
public static void main(String[] args) {
44+
// Replace the uri string with your MongoDB deployment's connection string
45+
String uri = "<connection string>";
46+
47+
MongoClient mongoClient = MongoClients.create(uri);
48+
MongoDatabase database = mongoClient.getDatabase("aggregation");
49+
MongoCollection<Document> collection = database.getCollection("restaurants");
50+
51+
// Paste the aggregation code here
52+
}
53+
}
54+
55+
.. tip::
56+
57+
To learn more about connecting to MongoDB, see the :ref:`Connection
58+
Guide <java-connect-to-mongodb>`.
59+
60+
Insert Sample Data
61+
++++++++++++++++++
62+
63+
.. literalinclude:: /includes/fundamentals/code-snippets/AggTour.java
64+
:language: java
65+
:dedent:
66+
:start-after: begin insert
67+
:end-before: end insert
68+
69+
Basic Aggregation Example
70+
~~~~~~~~~~~~~~~~~~~~~~~~~
71+
72+
To perform an aggregation, pass a list of aggregation stages to the
73+
``MongoCollection.aggregate()`` method.
74+
75+
The Java driver provides the
76+
`Aggregates <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Aggregates.html>`__
77+
helper class that contains builders for aggregation stages.
78+
79+
In the following example, the aggregation pipeline:
80+
81+
- Uses a :manual:`$match </reference/operator/aggregation/match/>` stage to filter for documents whose
82+
``categories`` array field contains the element ``Bakery``. The example uses
83+
``Aggregates.match`` to build the ``$match`` stage.
84+
85+
- Uses a :manual:`$group </reference/operator/aggregation/group/>` stage to group the matching documents by the ``stars``
86+
field, accumulating a count of documents for each distinct value of ``stars``.
87+
88+
.. note::
89+
90+
You can build the expressions used in this example using the :ref:`aggregation builders <aggregates-builders>`.
91+
92+
.. literalinclude:: /includes/fundamentals/code-snippets/AggTour.java
93+
:language: java
94+
:dedent:
95+
:start-after: begin aggregation basic
96+
:end-before: end aggregation basic
97+
98+
The preceding aggregation produces the following results:
99+
100+
.. code-block:: none
101+
:copyable: false
102+
103+
{"_id": 4, "count": 2}
104+
{"_id": 5, "count": 1}
105+
106+
For more information about the methods and classes mentioned in this section,
107+
see the following API Documentation:
108+
109+
- `MongoCollection.aggregate() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#aggregate(java.util.List)>`__
110+
- `Aggregates.match <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Aggregates.html#match(org.bson.conversions.Bson)>`__
111+
112+
Explain Aggregation Example
113+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
114+
115+
To view information about how MongoDB executes your operation, use the
116+
``explain()`` method of the ``AggregateIterable`` class. The ``explain()``
117+
method returns **execution plans** and performance statistics. An execution
118+
plan is a potential way MongoDB can complete an operation.
119+
The ``explain()`` method provides both the winning plan, which is the plan MongoDB
120+
executed, and any rejected plans.
121+
122+
.. tip::
123+
124+
To learn more about query plans and execution statistics, see
125+
:manual:`Explain Results </reference/explain-results/>` in the Server manual.
126+
127+
.. include:: /includes/fundamentals/explain-verbosity.rst
128+
129+
The following example prints the JSON representation of the
130+
winning plans for any aggregation stages that produce execution plans:
131+
132+
.. literalinclude:: /includes/fundamentals/code-snippets/AggTour.java
133+
:language: java
134+
:dedent:
135+
:start-after: begin aggregation explain
136+
:end-before: end aggregation explain
137+
138+
The example produces the following output as the ``$group`` stage
139+
is the only stage that produces an execution plan:
140+
141+
.. code-block:: none
142+
:copyable: false
143+
144+
{
145+
"stage": "GROUP",
146+
"planNodeId": 2,
147+
"inputStage": {
148+
"stage": "COLLSCAN",
149+
"planNodeId": 1,
150+
"filter": {
151+
"categories": {
152+
"$eq": "Bakery"
153+
}
154+
},
155+
"direction": "forward"
156+
}
157+
}
158+
159+
For more information about the topics mentioned in this section, see the
160+
following resources:
161+
162+
- :manual:`Explain Output </reference/explain-results/>` Server Manual Entry
163+
- :manual:`Query Plans </core/query-plans/>` Server Manual Entry
164+
- `ExplainVerbosity <{+api+}/apidocs/mongodb-driver-core/com/mongodb/ExplainVerbosity>`__ API Documentation
165+
- `explain() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/FindIterable.html#explain()>`__ API Documentation
166+
- `AggregateIterable <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/AggregateIterable.html>`__ API Documentation
167+
168+
Aggregation Expression Example
169+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
170+
171+
The {+driver-short+} provides builders for accumulator expressions for use with
172+
``$group``. You must declare all other expressions in JSON format or
173+
compatible document format.
174+
175+
.. tip::
176+
177+
The syntax in either of the following examples will define an :manual:`$arrayElemAt </reference/operator/aggregation/arrayElemAt/>`
178+
expression.
179+
180+
The ``$`` in front of "categories" tells MongoDB that this is a :manual:`field path </meta/aggregation-quick-reference/#expressions>`,
181+
using the ``categories`` field from the input document.
182+
183+
.. code-block:: java
184+
:copyable: false
185+
186+
new Document("$arrayElemAt", Arrays.asList("$categories", 0))
187+
188+
.. code-block:: java
189+
:copyable: false
190+
191+
Document.parse("{ $arrayElemAt: ['$categories', 0] }")
192+
193+
Alternatively, you can construct expressions by using the Aggregation
194+
Expression Operations API. To learn more, see
195+
:ref:`java-aggregation-expression-operations`.
196+
197+
In the following example, the aggregation pipeline uses a
198+
``$project`` stage and various ``Projections`` to return the ``name``
199+
field and the calculated field ``firstCategory`` whose value is the
200+
first element in the ``categories`` field.
201+
202+
.. literalinclude:: /includes/fundamentals/code-snippets/AggTour.java
203+
:language: java
204+
:dedent:
205+
:start-after: begin aggregation expression
206+
:end-before: end aggregation expression
207+
208+
The preceding aggregation produces the following results:
209+
210+
.. code-block:: none
211+
:copyable: false
212+
213+
{"name": "456 Cookies Shop", "firstCategory": "Bakery"}
214+
{"name": "Sun Bakery Trattoria", "firstCategory": "Pizza"}
215+
{"name": "456 Steak Restaurant", "firstCategory": "Steak"}
216+
{"name": "Blue Bagels Grill", "firstCategory": "Bagels"}
217+
{"name": "XYZ Steak Buffet", "firstCategory": "Steak"}
218+
{"name": "Hot Bakery Cafe", "firstCategory": "Bakery"}
219+
{"name": "Green Feast Pizzeria", "firstCategory": "Pizza"}
220+
{"name": "ZZZ Pasta Buffet", "firstCategory": "Pasta"}
221+
{"name": "XYZ Coffee Bar", "firstCategory": "Coffee"}
222+
{"name": "XYZ Bagels Restaurant", "firstCategory": "Bagels"}
223+
224+
For more information about the methods and classes mentioned in this section,
225+
see the following API Documentation:
226+
227+
- `Accumulators <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Accumulators.html>`__
228+
- `$group <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Aggregates.html#group(TExpression,java.util.List)>`__
229+
- `$project <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Aggregates.html#project(org.bson.conversions.Bson)>`__
230+
- `Projections <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Projections.html>`__

source/crud.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ CRUD Operations
1010
Insert Documents </crud/insert>
1111
Query Documents </crud/query-documents>
1212
Update Documents </crud/update-documents>
13+
Replace Documents </crud/replace-documents>
1314
Delete Documents </crud/delete>
1415
Bulk Operations </crud/bulk>
1516
Compound Operations </crud/compound-operations>

source/crud/replace-documents.txt

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
.. _java-replace-document:
2+
.. _replace-operation:
3+
4+
=================
5+
Replace Documents
6+
=================
7+
8+
.. contents:: On this page
9+
:local:
10+
:backlinks: none
11+
:depth: 2
12+
:class: singlecol
13+
14+
Overview
15+
--------
16+
17+
In this guide, you can learn how to replace documents in a MongoDB
18+
collection. A replace operation specifies the fields and values to replace
19+
a single document from your collection.
20+
21+
Replace One Method
22+
------------------
23+
24+
A replace operation substitutes one document from your collection. The
25+
substitution occurs between a document your query filter matches and a
26+
replacement document.
27+
28+
The `replaceOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#replaceOne(org.bson.conversions.Bson,TDocument)>`__
29+
method removes all the existing fields and values in the
30+
matching document (except the ``_id`` field) and substitutes it with the
31+
replacement document.
32+
33+
You can call the ``replaceOne()`` method on a ``MongoCollection``
34+
instance as follows:
35+
36+
.. code-block:: java
37+
38+
collection.replaceOne(<query>, <replacement>);
39+
40+
Replace Operation Parameters
41+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
42+
43+
The ``replaceOne()`` method has the following parameters:
44+
45+
- ``query`` specifies a query filter with the criteria to match a
46+
document to replace in your collection.
47+
- ``replacement`` specifies fields and values of a new ``Document``
48+
object to replace the matched document.
49+
- *(Optional)* ``replaceOptions`` specifies options that you can set to
50+
customize how the driver performs the replace operation. To learn more
51+
about this type, see the API documentation for `ReplaceOptions
52+
<{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/ReplaceOptions.html>`__.
53+
54+
Replace One Example
55+
~~~~~~~~~~~~~~~~~~~
56+
57+
In this example, a paint store sells five different
58+
colors of paint. The ``paint_inventory`` collection represents their
59+
current inventory:
60+
61+
.. code-block:: json
62+
63+
{ "_id": 1, "color": "red", "qty": 5 }
64+
{ "_id": 2, "color": "purple", "qty": 8 }
65+
{ "_id": 3, "color": "yellow", "qty": 0 }
66+
{ "_id": 4, "color": "green", "qty": 6 }
67+
{ "_id": 5, "color": "pink", "qty": 0 }
68+
69+
The paint store realizes they must update their inventory again. What they
70+
thought was 20 cans of pink paint is actually 25 cans of orange paint.
71+
72+
To update the inventory, call the ``replaceOne()`` method specifying the
73+
following:
74+
75+
- A query filter that matches documents where the ``color`` is "pink"
76+
- A replacement document where the ``color`` is "orange" and the ``qty`` is "25"
77+
78+
.. literalinclude:: /includes/fundamentals/code-snippets/Update.java
79+
:language: java
80+
:dedent:
81+
:start-after: begin replaceOneExample
82+
:end-before: end replaceOneExample
83+
84+
The output of the preceding code resembles the following:
85+
86+
.. code-block:: none
87+
:copyable: false
88+
89+
Matched document count: 1
90+
Modified document count: 1
91+
92+
The following shows the updated document:
93+
94+
.. code-block:: json
95+
:copyable: false
96+
97+
{ "_id": 5, "color": "orange", "qty": 25 }
98+
99+
If multiple documents match the query filter specified in
100+
the ``replaceOne()`` method, it replaces the first result. You can
101+
specify a sort in a ``ReplaceOptions`` instance to apply an order to
102+
matched documents before the server performs the replace operation, as
103+
shown in the following code:
104+
105+
.. literalinclude:: /includes/fundamentals/code-snippets/Update.java
106+
:language: java
107+
:dedent:
108+
:start-after: begin replaceoptions
109+
:end-before: end replaceoptions
110+
111+
If zero documents match the query filter in the replace operation,
112+
``replaceOne()`` makes no changes to documents in the collection. See
113+
our :ref:`upsert guide <java-upsert>` to
114+
learn how to insert a new document instead of replacing one if no
115+
documents match.
116+
117+
.. important::
118+
119+
The ``replaceOne()`` method cannot make changes to a document that
120+
violate unique index constraints on the collection.
121+
For more information about constraints on unique indexes,
122+
see :manual:`Unique Indexes </core/index-unique/>` in the
123+
{+mdb-server+} manual.

0 commit comments

Comments
 (0)