Skip to content

Commit 894ab5b

Browse files
committed
DOCSP-33664: fix explain agg code + other fixes (#503)
* DOCSP-33664: fix explain agg code + other fixes * small fixes (cherry picked from commit b34c2d6) (cherry picked from commit 7522203)
1 parent d748ef4 commit 894ab5b

File tree

5 files changed

+116
-83
lines changed

5 files changed

+116
-83
lines changed

source/compatibility.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ Compatibility
2121
:depth: 2
2222
:class: singlecol
2323

24+
Connect to a Compatible MongoDB Deployment
25+
------------------------------------------
2426

2527
You can use the {+driver-short+} to connect to deployments hosted in the
2628
following environments:

source/fundamentals/aggregation.txt

Lines changed: 82 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,16 @@
1+
.. _java-aggregation:
2+
13
===========
24
Aggregation
35
===========
46

7+
.. facet::
8+
:name: genre
9+
:values: reference
10+
11+
.. meta::
12+
:keywords: code example, transform, computed
13+
514
.. contents:: On this page
615
:local:
716
:backlinks: none
@@ -11,37 +20,41 @@ Aggregation
1120
Overview
1221
--------
1322

14-
.. _java-aggregation:
15-
16-
In this guide, you can learn how to use **aggregation operations** in the MongoDB Java driver.
23+
In this guide, you can learn how to use the {+driver-short+} to perform
24+
**aggregation operations**.
1725

18-
Aggregation operations process data in your MongoDB collections and return computed results. MongoDB's Aggregation
19-
pipeline, part of the Query API, is modeled on the concept of data processing pipelines. Documents enter a multi-staged pipeline that
20-
transforms the documents into an aggregated result.
26+
Aggregation operations process data in your MongoDB collections and
27+
return computed results. The MongoDB Aggregation framework, which is
28+
part of the Query API, is modeled on the concept of data processing
29+
pipelines. Documents enter a pipeline comprised of one or more stages,
30+
and this pipeline transforms the documents into an aggregated result.
2131

22-
Another way to think of aggregation is like a car factory. Within the car factory is an assembly line, along which
23-
are assembly stations with specialized tools to do a specific job, like drills and welders. Raw parts enter the factory,
24-
which are then transformed and assembled into a finished product.
32+
An aggregation operation is similar to a car factory. A car factory has
33+
an assembly line, which contains assembly stations with specialized
34+
tools to do specific jobs, like drills and welders. Raw parts enter the
35+
factory, and then the assembly line transforms and assembles them into a
36+
finished product.
2537

26-
The **aggregation pipeline** is the assembly line, **aggregation stages** are the assembly stations, and
27-
**operator expressions** are the specialized tools.
38+
The **aggregation pipeline** is the assembly line, **aggregation
39+
stages** are the assembly stations, and **operator expressions** are the
40+
specialized tools.
2841

29-
Aggregation and Find Operations Compared
30-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
42+
Compare Aggregation and Find Operations
43+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3144

32-
Using ``find`` operations, you can:
45+
You can use find operations to perform the following actions:
3346

34-
- select *what* documents to return
35-
- select *what* fields to return
36-
- sort the results
47+
- Select *what* documents to return
48+
- Select *what* fields to return
49+
- Sort the results
3750

38-
Using ``aggregation`` operations, you can:
51+
You can use aggregation operations to perform the following actions:
3952

40-
- perform all ``find`` operations
41-
- rename fields
42-
- calculate fields
43-
- summarize data
44-
- group values
53+
- Perform find operations
54+
- Rename fields
55+
- Calculate fields
56+
- Summarize data
57+
- Group values
4558

4659
Aggregation operations have some :manual:`limitations </core/aggregation-pipeline-limits/>` you must keep in mind:
4760

@@ -68,8 +81,8 @@ Useful References
6881
Runnable Examples
6982
-----------------
7083

71-
Base Setup
72-
~~~~~~~~~~
84+
Import Classes
85+
~~~~~~~~~~~~~~
7386

7487
Create a new Java file called ``AggTour.java`` and include the following import statements:
7588

@@ -79,7 +92,6 @@ Create a new Java file called ``AggTour.java`` and include the following import
7992
:start-after: begin imports
8093
:end-before: end imports
8194

82-
8395
Connect to a MongoDB Deployment
8496
+++++++++++++++++++++++++++++++
8597

@@ -89,22 +101,23 @@ Connect to a MongoDB Deployment
89101

90102
public static void main(String[] args) {
91103
// Replace the uri string with your MongoDB deployment's connection string
92-
String uri = "<connection string uri>";
104+
String uri = "<connection string>";
93105

94106
MongoClient mongoClient = MongoClients.create(uri);
95107
MongoDatabase database = mongoClient.getDatabase("aggregation");
96108
MongoCollection<Document> collection = database.getCollection("restaurants");
97109

98-
// aggregation here
110+
// Paste the aggregation code here
99111
}
100112
}
101113

102-
.. seealso::
114+
.. tip::
103115

104-
For information on connecting to MongoDB, see the :ref:`Connection Guide <mongoclient>`
116+
To learn more about connecting to MongoDB, see the :ref:`Connection
117+
Guide <connect-to-mongodb>`.
105118

106-
Insert the Data
107-
+++++++++++++++
119+
Insert Sample Data
120+
++++++++++++++++++
108121

109122
.. literalinclude:: /includes/fundamentals/code-snippets/AggTour.java
110123
:language: java
@@ -131,15 +144,15 @@ In the following example, the aggregation pipeline:
131144
- Uses a :manual:`$group </reference/operator/aggregation/group/>` stage to group the matching documents by the ``stars``
132145
field, accumulating a count of documents for each distinct value of ``stars``.
133146

134-
.. seealso::
147+
.. note::
135148

136149
You can build the expressions used in this example using the :ref:`aggregation builders <aggregates-builders>`.
137150

138151
.. literalinclude:: /includes/fundamentals/code-snippets/AggTour.java
139152
:language: java
140153
:dedent:
141-
:start-after: begin aggregation one
142-
:end-before: end aggregation one
154+
:start-after: begin aggregation basic
155+
:end-before: end aggregation basic
143156

144157
The preceding aggregation should produce the following results:
145158

@@ -162,32 +175,45 @@ To view information about how MongoDB executes your operation, use the
162175
``explain()`` method of the ``AggregateIterable`` class. The ``explain()``
163176
method returns **execution plans** and performance statistics. An execution
164177
plan is a potential way MongoDB can complete an operation.
165-
The ``explain()`` method provides both the winning plan (the plan MongoDB
166-
executed) and rejected plans.
178+
The ``explain()`` method provides both the winning plan, which is the plan MongoDB
179+
executed, and any rejected plans.
180+
181+
.. tip::
182+
183+
To learn more about query plans and execution statistics, see
184+
:manual:`Explain Results </reference/explain-results/>` in the Server manual.
167185

168186
.. include:: /includes/fundamentals/explain-verbosity.rst
169187

170-
In the following example, we print the JSON representation of the
171-
winning plans for aggregation stages that produce execution plans:
188+
The following example prints the JSON representation of the
189+
winning plans for any aggregation stages that produce execution plans:
172190

173191
.. literalinclude:: /includes/fundamentals/code-snippets/AggTour.java
174192
:language: java
175193
:dedent:
176-
:start-after: begin aggregation three
177-
:end-before: end aggregation three
194+
:start-after: begin aggregation explain
195+
:end-before: end aggregation explain
178196

179-
The preceding code snippet should produce the following output:
197+
The example produces the following output as the ``$group`` stage
198+
is the only stage that produces an execution plan:
180199

181200
.. code-block:: none
182201
:copyable: false
183202

184-
{ "stage": "PROJECTION_SIMPLE",
185-
"transformBy": {"stars": 1, "_id": 0},
203+
{
204+
"stage": "GROUP",
205+
"planNodeId": 2,
186206
"inputStage": {
187-
"stage": "COLLSCAN",
188-
"filter": {
189-
"categories": {"$eq":"bakery"}},
190-
"direction": "forward"}}
207+
"stage": "COLLSCAN",
208+
"planNodeId": 1,
209+
"filter": {
210+
"categories": {
211+
"$eq": "Bakery"
212+
}
213+
},
214+
"direction": "forward"
215+
}
216+
}
191217

192218
For more information about the topics mentioned in this section, see the
193219
following resources:
@@ -201,7 +227,7 @@ following resources:
201227
Aggregation Expression Example
202228
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
203229

204-
The Java driver provides builders for accumulator expressions for use with
230+
The {+driver-short+} provides builders for accumulator expressions for use with
205231
``$group``. You must declare all other expressions in JSON format or
206232
compatible document format.
207233

@@ -211,7 +237,7 @@ compatible document format.
211237
expression.
212238

213239
The ``$`` in front of "categories" tells MongoDB that this is a :manual:`field path </meta/aggregation-quick-reference/#expressions>`,
214-
using the "categories" field from the input document.
240+
using the ``categories`` field from the input document.
215241

216242
.. code-block:: java
217243
:copyable: false
@@ -223,6 +249,10 @@ compatible document format.
223249

224250
Document.parse("{ $arrayElemAt: ['$categories', 0] }")
225251

252+
Alternatively, you can construct expressions by using the Aggregation
253+
Expression Operations API. To learn more, see
254+
:ref:`java-aggregation-expression-operations`.
255+
226256
In the following example, the aggregation pipeline uses a
227257
``$project`` stage and various ``Projections`` to return the ``name``
228258
field and the calculated field ``firstCategory`` whose value is the
@@ -231,8 +261,8 @@ first element in the ``categories`` field.
231261
.. literalinclude:: /includes/fundamentals/code-snippets/AggTour.java
232262
:language: java
233263
:dedent:
234-
:start-after: begin aggregation two
235-
:end-before: end aggregation two
264+
:start-after: begin aggregation expression
265+
:end-before: end aggregation expression
236266

237267
The preceding aggregation should produce the following results:
238268

source/includes/fact-environments.rst

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
- `MongoDB Atlas
2-
<https://www.mongodb.com/docs/atlas>`__: The fully
2+
<https://www.mongodb.com/docs/atlas>`__: the fully
33
managed service for MongoDB deployments in the cloud
4-
- :ref:`MongoDB Enterprise <install-mdb-enterprise>`: The
4+
- :ref:`MongoDB Enterprise <install-mdb-enterprise>`: the
55
subscription-based, self-managed version of MongoDB
6-
- :ref:`MongoDB Community <install-mdb-community-edition>`: The
7-
source-available, free-to-use, and self-managed version of MongoDB
6+
- :ref:`MongoDB Community <install-mdb-community-edition>`: the
7+
source-available, free-to-use, and self-managed version of MongoDB
Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package docs.aggregation;
22

33
// begin imports
4-
54
import com.mongodb.client.MongoClient;
65
import com.mongodb.client.MongoClients;
76
import com.mongodb.client.MongoCollection;
@@ -12,18 +11,18 @@
1211
import com.mongodb.client.model.Filters;
1312
import com.mongodb.client.model.Projections;
1413
import org.bson.Document;
14+
import org.bson.json.JsonWriterSettings;
1515

1616
import java.util.Arrays;
1717
import java.util.List;
18-
1918
// end imports
2019

2120
// begin class intro
2221
// begin connection
2322
public class AggTour {
2423
public static void main(String[] args) {
2524
// Replace the uri string with your MongoDB deployment's connection string
26-
final String uri = "<connection string uri>";
25+
final String uri = "<connection string>";
2726

2827
MongoClient mongoClient = MongoClients.create(uri);
2928
MongoDatabase database = mongoClient.getDatabase("aggregation");
@@ -49,37 +48,36 @@ public static void main(String[] args) {
4948
// end insert
5049

5150
// Creates an aggregation pipeline that matches documents, groups them by the "stars" field, and tallies them by distinct values
52-
// begin aggregation one
51+
// begin aggregation basic
5352
collection.aggregate(
5453
Arrays.asList(
5554
Aggregates.match(Filters.eq("categories", "Bakery")),
5655
Aggregates.group("$stars", Accumulators.sum("count", 1))
5756
)
5857
// Prints the result of the aggregation operation as JSON
5958
).forEach(doc -> System.out.println(doc.toJson()));
60-
// end aggregation one
59+
// end aggregation basic
6160

62-
// begin aggregation three
61+
// begin aggregation explain
6362
Document explanation = collection.aggregate(
64-
Arrays.asList(
65-
Aggregates.match(Filters.eq("categories", "Bakery")),
66-
Aggregates.group("$stars", Accumulators.sum("count", 1))
67-
)
63+
Arrays.asList(
64+
Aggregates.match(Filters.eq("categories", "Bakery")),
65+
Aggregates.group("$stars", Accumulators.sum("count", 1))
66+
)
6867
).explain(ExplainVerbosity.EXECUTION_STATS);
6968

70-
List<Document> stages = explanation.get("stages", List.class);
71-
List<String> keys = Arrays.asList("queryPlanner", "winningPlan");
69+
String winningPlans = explanation
70+
.getEmbedded(
71+
Arrays.asList("queryPlanner", "winningPlan", "queryPlan"),
72+
Document.class
73+
)
74+
.toJson(JsonWriterSettings.builder().indent(true).build());
75+
76+
System.out.println(winningPlans);
77+
// end aggregation explain
7278

73-
// Prints the JSON representation of the winning execution plans
74-
for (Document stage : stages) {
75-
Document cursorStage = stage.get("$cursor", Document.class);
76-
if (cursorStage != null) {
77-
System.out.println(cursorStage.getEmbedded(keys, Document.class).toJson());
78-
}
79-
}
80-
// end aggregation three
8179
// Prints the restaurant name and the first value in the "categories" array as a field named "firstCategory"
82-
// begin aggregation two
80+
// begin aggregation expression
8381
collection.aggregate(
8482
Arrays.asList(
8583
Aggregates.project(
@@ -88,12 +86,15 @@ public static void main(String[] args) {
8886
Projections.include("name"),
8987
Projections.computed(
9088
"firstCategory",
91-
new Document("$arrayElemAt", Arrays.asList("$categories", 0))
89+
new Document(
90+
"$arrayElemAt",
91+
Arrays.asList("$categories", 0)
92+
)
9293
)
9394
)
9495
)
9596
)
9697
).forEach(doc -> System.out.println(doc.toJson()));
97-
// end aggregation two
98+
// end aggregation expression
9899
}
99100
}

source/index.txt

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,11 @@ If your Java application requires asynchronous stream processing, use the
4545
:driver:`Reactive Streams Driver </reactive-streams/>` which uses Reactive
4646
Streams to make non-blocking calls to MongoDB.
4747

48-
Compatibility
49-
-------------
48+
Connect to a Compatible MongoDB Deployment
49+
------------------------------------------
5050

51-
You can use the {+driver-short+} to connect to deployments hosted in the
52-
following environments:
51+
You can use the {+driver-short+} to connect to MongoDB
52+
deployments running on one of the following hosted services or editions:
5353

5454
.. include:: /includes/fact-environments.rst
5555

0 commit comments

Comments
 (0)