|
| 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>`__ |
0 commit comments