diff --git a/config/redirects b/config/redirects index bfe5774c4..8fa1740a3 100644 --- a/config/redirects +++ b/config/redirects @@ -14,61 +14,61 @@ raw: ${prefix}/master -> ${base}/upcoming/ [*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/change-a-document/ -> ${base}/${version}/fundamentals/crud/write-operations/modify/ [*-v4.10]: ${prefix}/${version}/fundamentals/connection/socks/ -> ${base}/${version}/ [*-v4.8]: ${prefix}/${version}/connection-troubleshooting/ -> ${base}/${version}/ -[master]: ${prefix}/${version}/fundamentals/crud/ -> ${base}/${version}/crud/ -[master]: ${prefix}/${version}/fundamentals/crud/read-operations/ -> ${base}/${version}/crud/read-operations/ -[master]: ${prefix}/${version}/fundamentals/crud/read-operations/retrieve/ -> ${base}/${version}/crud/read-operations/retrieve/ -[master]: ${prefix}/${version}/fundamentals/crud/read-operations/cursor/ -> ${base}/${version}/crud/read-operations/cursor/ -[master]: ${prefix}/${version}/fundamentals/crud/read-operations/change-streams/ -> ${base}/${version}/logging-monitoring/change-streams/ -[master]: ${prefix}/${version}/fundamentals/crud/read-operations/sort/ -> ${base}/${version}/crud/read-operations/sort/ -[master]: ${prefix}/${version}/fundamentals/crud/read-operations/skip/ -> ${base}/${version}/crud/read-operations/skip/ -[master]: ${prefix}/${version}/fundamentals/crud/read-operations/limit/ -> ${base}/${version}/crud/read-operations/limit/ -[master]: ${prefix}/${version}/fundamentals/crud/read-operations/project/ -> ${base}/${version}/crud/read-operations/project/ -[master]: ${prefix}/${version}/fundamentals/crud/read-operations/geo/ -> ${base}/${version}/crud/read-operations/geo/ -[master]: ${prefix}/${version}/fundamentals/crud/read-operations/text/ -> ${base}/${version}/crud/read-operations/text/ -[master]: ${prefix}/${version}/fundamentals/crud/write-operations/ -> ${base}/${version}/crud/write-operations/ -[master]: ${prefix}/${version}/fundamentals/crud/write-operations/insert/ -> ${base}/${version}/crud/write-operations/insert/ -[master]: ${prefix}/${version}/fundamentals/crud/write-operations/delete/ -> ${base}/${version}/crud/write-operations/delete/ -[master]: ${prefix}/${version}/fundamentals/crud/write-operations/modify/ -> ${base}/${version}/crud/write-operations/modify/ -[master]: ${prefix}/${version}/fundamentals/crud/write-operations/embedded-arrays/ -> ${base}/${version}/crud/write-operations/embedded-arrays/ -[master]: ${prefix}/${version}/fundamentals/crud/write-operations/upsert/ -> ${base}/${version}/crud/write-operations/upsert/ -[master]: ${prefix}/${version}/fundamentals/crud/write-operations/bulk/ -> ${base}/${version}/crud/write-operations/bulk/ -[master]: ${prefix}/${version}/fundamentals/crud/query-document/ -> ${base}/${version}/crud/query-document/ -[master]: ${prefix}/${version}/fundamentals/crud/compound-operations/ -> ${base}/${version}/crud/compound-operations/ -[master]: ${prefix}/${version}/fundamentals/data-formats/ -> ${base}/${version}/data-formats/ -[master]: ${prefix}/${version}/fundamentals/data-formats/document-data-format-bson/ -> ${base}/${version}/data-formats/document-data-format-bson/ -[master]: ${prefix}/${version}/fundamentals/data-formats/document-data-format-extended-json/ -> ${base}/${version}/data-formats/document-data-format-extended-json/ -[master]: ${prefix}/${version}/fundamentals/data-formats/documents/ -> ${base}/${version}/data-formats/documents/ -[master]: ${prefix}/${version}/fundamentals/data-formats/document-data-format-pojo/ -> ${base}/${version}/data-formats/document-data-format-pojo/ -[master]: ${prefix}/${version}/fundamentals/data-formats/document-data-format-record/ -> ${base}/${version}/data-formats/document-data-format-record/ -[master]: ${prefix}/${version}/fundamentals/data-formats/pojo-customization/ -> ${base}/${version}/data-formats/pojo-customization/ -[master]: ${prefix}/${version}/fundamentals/data-formats/codecs/ -> ${base}/${version}/data-formats/codecs/ -[master]: ${prefix}/${version}/fundamentals/connection/ -> ${base}/${version}/connection/ -[master]: ${prefix}/${version}/fundamentals/connection/connect/ -> ${base}/${version}/connection/mongoclient -[master]: ${prefix}/${version}/fundamentals/connection/connection-options/ -> ${base}/${version}/connection/connection-options/ -[master]: ${prefix}/${version}/fundamentals/connection/mongoclientsettings/ -> ${base}/${version}/connection/mongoclientsettings/ -[master]: ${prefix}/${version}/fundamentals/connection/network-compression/ -> ${base}/${version}/connection/network-compression/ -[master]: ${prefix}/${version}/fundamentals/connection/socks/ -> ${base}/${version}/connection/socks/ -[master]: ${prefix}/${version}/fundamentals/connection/tls/ -> ${base}/${version}/security/tls/ -[master]: ${prefix}/${version}/fundamentals/connection/jndi/ -> ${base}/${version}/connection/jndi/ -[master]: ${prefix}/${version}/fundamentals/builders/ -> ${base}/${version}/crud/builders/ -[master]: ${prefix}/${version}/fundamentals/builders/aggregates/ -> ${base}/${version}/crud/builders/aggregates/ -[master]: ${prefix}/${version}/fundamentals/builders/filters/ -> ${base}/${version}/crud/builders/filters/ -[master]: ${prefix}/${version}/fundamentals/builders/indexes/ -> ${base}/${version}/crud/builders/indexes/ -[master]: ${prefix}/${version}/fundamentals/builders/projections/ -> ${base}/${version}/crud/builders/projections/ -[master]: ${prefix}/${version}/fundamentals/builders/sort/ -> ${base}/${version}/crud/builders/sort/ -[master]: ${prefix}/${version}/fundamentals/builders/updates/ -> ${base}/${version}/crud/builders/updates/ -[master]: ${prefix}/${version}/fundamentals/builders/vector-search -> ${base}/${version}/atlas-vector-search/ -[master]: ${prefix}/${version}/fundamentals/aggregation/ -> ${base}/${version}/crud/aggregation/ -[master]: ${prefix}/${version}/fundamentals/aggregation-expression-operations/ -> ${base}/${version}/crud/aggregation-expression-operations/ -[master]: ${prefix}/${version}/fundamentals/collations/ -> ${base}/${version}/crud/collations/ -[master]: ${prefix}/${version}/fundamentals/stable-api/ -> ${base}/${version}/connection/stable-api/ -[master]: ${prefix}/${version}/connection-troubleshooting/ -> ${base}/${version}/connection/connection-troubleshooting/ -[master]: ${prefix}/${version}/fundamentals/gridfs/ -> ${base}/${version}/crud/gridfs/ -[master]: ${prefix}/${version}/fundamentals/transactions/ -> ${base}/${version}/crud/transactions/ -[master]: ${prefix}/${version}/fundamentals/time-series/ -> ${base}/${version}/data-formats/time-series/ -[master]: ${prefix}/${version}/quick-start/ -> ${base}/${version}/getting-started/ -[master]: ${prefix}/${version}/fundamentals/databases-collections/ -> ${base}/${version}/getting-started/databases-collections/ -[master]: ${prefix}/${version}/integrations/ -> ${base}/${version}/getting-started/integrations/ -[master]: ${prefix}/${version}/quick-reference/ -> ${base}/${version}/getting-started/quick-reference/ -[master]: ${prefix}/${version}/fundamentals/enterprise-auth/ -> ${base}/${version}/security/enterprise-auth/ -[master]: ${prefix}/${version}/connection/socks/ -> ${base}/${version}/security/socks/ +[*-master]: ${prefix}/${version}/fundamentals/crud/ -> ${base}/${version}/crud/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/ -> ${base}/${version}/crud/query-documents/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/retrieve/ -> ${base}/${version}/crud/query-documents/find/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/cursor/ -> ${base}/${version}/crud/query-documents/cursor/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/change-streams/ -> ${base}/${version}/logging-monitoring/change-streams/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/sort/ -> ${base}/${version}/crud/query-documents/sort/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/skip/ -> ${base}/${version}/crud/query-documents/skip/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/limit/ -> ${base}/${version}/crud/query-documents/limit/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/project/ -> ${base}/${version}/crud/query-documents/project/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/geo/ -> ${base}/${version}/crud/query-documents/geo/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/text/ -> ${base}/${version}/crud/query-documents/text/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/ -> ${base}/${version}/crud/insert/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/insert/ -> ${base}/${version}/crud/insert/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/delete/ -> ${base}/${version}/crud/update-documents/delete/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/modify/ -> ${base}/${version}/crud/update-documents/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/embedded-arrays/ -> ${base}/${version}/crud/update-documents/embedded-arrays/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/upsert/ -> ${base}/${version}/crud/update-documents/upsert/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/bulk/ -> ${base}/${version}/crud/bulk/ +[*-master]: ${prefix}/${version}/fundamentals/crud/query-document/ -> ${base}/${version}/crud/query-documents/specify-query/ +[*-master]: ${prefix}/${version}/fundamentals/crud/compound-operations/ -> ${base}/${version}/crud/compound-operations/ +[*-master]: ${prefix}/${version}/fundamentals/data-formats/ -> ${base}/${version}/data-formats/ +[*-master]: ${prefix}/${version}/fundamentals/data-formats/document-data-format-bson/ -> ${base}/${version}/data-formats/document-data-format-bson/ +[*-master]: ${prefix}/${version}/fundamentals/data-formats/document-data-format-extended-json/ -> ${base}/${version}/data-formats/document-data-format-extended-json/ +[*-master]: ${prefix}/${version}/fundamentals/data-formats/documents/ -> ${base}/${version}/data-formats/documents/ +[*-master]: ${prefix}/${version}/fundamentals/data-formats/document-data-format-pojo/ -> ${base}/${version}/data-formats/document-data-format-pojo/ +[*-master]: ${prefix}/${version}/fundamentals/data-formats/document-data-format-record/ -> ${base}/${version}/data-formats/document-data-format-record/ +[*-master]: ${prefix}/${version}/fundamentals/data-formats/pojo-customization/ -> ${base}/${version}/data-formats/pojo-customization/ +[*-master]: ${prefix}/${version}/fundamentals/data-formats/codecs/ -> ${base}/${version}/data-formats/codecs/ +[*-master]: ${prefix}/${version}/fundamentals/connection/ -> ${base}/${version}/connection/ +[*-master]: ${prefix}/${version}/fundamentals/connection/connect/ -> ${base}/${version}/connection/mongoclient +[*-master]: ${prefix}/${version}/fundamentals/connection/connection-options/ -> ${base}/${version}/connection/connection-options/ +[*-master]: ${prefix}/${version}/fundamentals/connection/mongoclientsettings/ -> ${base}/${version}/connection/mongoclientsettings/ +[*-master]: ${prefix}/${version}/fundamentals/connection/network-compression/ -> ${base}/${version}/connection/network-compression/ +[*-master]: ${prefix}/${version}/fundamentals/connection/socks/ -> ${base}/${version}/connection/socks/ +[*-master]: ${prefix}/${version}/fundamentals/connection/tls/ -> ${base}/${version}/security/tls/ +[*-master]: ${prefix}/${version}/fundamentals/connection/jndi/ -> ${base}/${version}/connection/jndi/ +[*-master]: ${prefix}/${version}/fundamentals/builders/ -> ${base}/${version}/builders/ +[*-master]: ${prefix}/${version}/fundamentals/builders/aggregates/ -> ${base}/${version}/builders/aggregates/ +[*-master]: ${prefix}/${version}/fundamentals/builders/filters/ -> ${base}/${version}/builders/filters/ +[*-master]: ${prefix}/${version}/fundamentals/builders/indexes/ -> ${base}/${version}/builders/indexes/ +[*-master]: ${prefix}/${version}/fundamentals/builders/projections/ -> ${base}/${version}/builders/projections/ +[*-master]: ${prefix}/${version}/fundamentals/builders/sort/ -> ${base}/${version}/builders/sort/ +[*-master]: ${prefix}/${version}/fundamentals/builders/updates/ -> ${base}/${version}/builders/updates/ +[*-master]: ${prefix}/${version}/fundamentals/builders/vector-search -> ${base}/${version}/atlas-vector-search/ +[*-master]: ${prefix}/${version}/fundamentals/aggregation/ -> ${base}/${version}/aggregation/ +[*-master]: ${prefix}/${version}/fundamentals/aggregation-expression-operations/ -> ${base}/${version}/aggregation/aggregation-expression-operations/ +[*-master]: ${prefix}/${version}/fundamentals/collations/ -> ${base}/${version}/crud/collations/ +[*-master]: ${prefix}/${version}/fundamentals/stable-api/ -> ${base}/${version}/connection/stable-api/ +[*-master]: ${prefix}/${version}/connection-troubleshooting/ -> ${base}/${version}/connection/connection-troubleshooting/ +[*-master]: ${prefix}/${version}/fundamentals/gridfs/ -> ${base}/${version}/crud/gridfs/ +[*-master]: ${prefix}/${version}/fundamentals/transactions/ -> ${base}/${version}/crud/transactions/ +[*-master]: ${prefix}/${version}/fundamentals/time-series/ -> ${base}/${version}/data-formats/time-series/ +[*-master]: ${prefix}/${version}/quick-start/ -> ${base}/${version}/getting-started/ +[*-master]: ${prefix}/${version}/fundamentals/databases-collections/ -> ${base}/${version}/getting-started/databases-collections/ +[*-master]: ${prefix}/${version}/integrations/ -> ${base}/${version}/getting-started/integrations/ +[*-master]: ${prefix}/${version}/quick-reference/ -> ${base}/${version}/getting-started/quick-reference/ +[*-master]: ${prefix}/${version}/fundamentals/enterprise-auth/ -> ${base}/${version}/security/enterprise-auth/ +[*-master]: ${prefix}/${version}/connection/socks/ -> ${base}/${version}/security/socks/ diff --git a/snooty.toml b/snooty.toml index e550a15d9..34305fdbd 100644 --- a/snooty.toml +++ b/snooty.toml @@ -7,12 +7,14 @@ intersphinx = [ ] toc_landing_pages = [ - "/get-started", "/connection", "/connection/specify-connection-options", - "/crud", - "/crud/builders", + "/crud/update-documents", + "/aggregation", + "/builders", "/data-formats", + "/references", + "/logging-monitoring", "/api-documentation", "/security", "/security/auth" diff --git a/source/aggregation.txt b/source/aggregation.txt new file mode 100644 index 000000000..e16972d2f --- /dev/null +++ b/source/aggregation.txt @@ -0,0 +1,91 @@ +.. _java-aggregation: + +=========== +Aggregation +=========== + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example, transform, computed + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. toctree:: + :caption: Aggregation + + Aggregation Expressions + Aggregation Examples + +Overview +-------- + +In this guide, you can learn how to use the {+driver-short+} to perform +**aggregation operations**. + +Aggregation operations process data in your MongoDB collections and +return computed results. The MongoDB Aggregation framework, which is +part of the Query API, is modeled on the concept of data processing +pipelines. Documents enter a pipeline comprised of one or more stages, +and this pipeline transforms the documents into an aggregated result. + +An aggregation operation is similar to a car factory. A car factory has +an assembly line, which contains assembly stations with specialized +tools to do specific jobs, like drills and welders. Raw parts enter the +factory, and then the assembly line transforms and assembles them into a +finished product. + +The **aggregation pipeline** is the assembly line, **aggregation +stages** are the assembly stations, and **operator expressions** are the +specialized tools. + +For more information about aggregation in the {+driver-short+}, see the +following pages: + +- :ref:`` +- :ref:`` + +Compare Aggregation and Find Operations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can use find operations to perform the following actions: + +- Select *what* documents to return +- Select *what* fields to return +- Sort the results + +You can use aggregation operations to perform the following actions: + +- Perform find operations +- Rename fields +- Calculate fields +- Summarize data +- Group values + +Aggregation operations have some :manual:`limitations ` you must keep in mind: + +- Returned documents must not violate the :manual:`BSON document size limit ` + of 16 megabytes. + +- Pipeline stages have a memory limit of 100 megabytes by default. If required, you can exceed this limit by using + the `allowDiskUse <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/AggregateIterable.html#allowDiskUse(java.lang.Boolean)>`__ + method. + + .. important:: ``$graphLookup`` exception + + The :manual:`$graphLookup ` stage has a strict memory limit of 100 megabytes + and will ignore ``allowDiskUse``. + +Useful References +~~~~~~~~~~~~~~~~~ + +- :manual:`Aggregation pipeline ` +- :manual:`Aggregation stages ` +- :manual:`Operator expressions ` +- :ref:`Aggregation Builders ` diff --git a/source/crud/aggregation.txt b/source/aggregation/aggregation-examples.txt similarity index 76% rename from source/crud/aggregation.txt rename to source/aggregation/aggregation-examples.txt index defdb8d4e..576c9d7e5 100644 --- a/source/crud/aggregation.txt +++ b/source/aggregation/aggregation-examples.txt @@ -1,8 +1,8 @@ -.. _java-aggregation: +.. _java-aggregation-examples: -=========== -Aggregation -=========== +==================== +Aggregation Examples +==================== .. facet:: :name: genre @@ -20,66 +20,7 @@ Aggregation Overview -------- -In this guide, you can learn how to use the {+driver-short+} to perform -**aggregation operations**. - -Aggregation operations process data in your MongoDB collections and -return computed results. The MongoDB Aggregation framework, which is -part of the Query API, is modeled on the concept of data processing -pipelines. Documents enter a pipeline comprised of one or more stages, -and this pipeline transforms the documents into an aggregated result. - -An aggregation operation is similar to a car factory. A car factory has -an assembly line, which contains assembly stations with specialized -tools to do specific jobs, like drills and welders. Raw parts enter the -factory, and then the assembly line transforms and assembles them into a -finished product. - -The **aggregation pipeline** is the assembly line, **aggregation -stages** are the assembly stations, and **operator expressions** are the -specialized tools. - -Compare Aggregation and Find Operations -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can use find operations to perform the following actions: - -- Select *what* documents to return -- Select *what* fields to return -- Sort the results - -You can use aggregation operations to perform the following actions: - -- Perform find operations -- Rename fields -- Calculate fields -- Summarize data -- Group values - -Aggregation operations have some :manual:`limitations ` you must keep in mind: - -- Returned documents must not violate the :manual:`BSON document size limit ` - of 16 megabytes. - -- Pipeline stages have a memory limit of 100 megabytes by default. If required, you can exceed this limit by using - the `allowDiskUse <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/AggregateIterable.html#allowDiskUse(java.lang.Boolean)>`__ - method. - - .. important:: ``$graphLookup`` exception - - The :manual:`$graphLookup ` stage has a strict memory limit of 100 megabytes - and will ignore ``allowDiskUse``. - -Useful References -~~~~~~~~~~~~~~~~~ - -- :manual:`Aggregation pipeline ` -- :manual:`Aggregation stages ` -- :manual:`Operator expressions ` -- :ref:`Aggregation Builders ` - -Runnable Examples ------------------ +This page demonstrates how to use aggregation pipelines. Import Classes ~~~~~~~~~~~~~~ diff --git a/source/crud/aggregation-expression-operations.txt b/source/aggregation/aggregation-expression-operations.txt similarity index 100% rename from source/crud/aggregation-expression-operations.txt rename to source/aggregation/aggregation-expression-operations.txt diff --git a/source/crud/builders.txt b/source/builders.txt similarity index 92% rename from source/crud/builders.txt rename to source/builders.txt index eb906a6b4..1311f8f74 100644 --- a/source/crud/builders.txt +++ b/source/builders.txt @@ -6,12 +6,12 @@ Builders .. toctree:: - Aggregation - Filters - Indexes - Projection - Sort - Update + Aggregation + Filters + Indexes + Projection + Sort + Update .. contents:: On this page :local: diff --git a/source/crud/builders/aggregates.txt b/source/builders/aggregates.txt similarity index 100% rename from source/crud/builders/aggregates.txt rename to source/builders/aggregates.txt diff --git a/source/crud/builders/filters.txt b/source/builders/filters.txt similarity index 100% rename from source/crud/builders/filters.txt rename to source/builders/filters.txt diff --git a/source/crud/builders/indexes.txt b/source/builders/indexes.txt similarity index 100% rename from source/crud/builders/indexes.txt rename to source/builders/indexes.txt diff --git a/source/crud/builders/projections.txt b/source/builders/projections.txt similarity index 100% rename from source/crud/builders/projections.txt rename to source/builders/projections.txt diff --git a/source/crud/builders/sort.txt b/source/builders/sort.txt similarity index 100% rename from source/crud/builders/sort.txt rename to source/builders/sort.txt diff --git a/source/crud/builders/updates.txt b/source/builders/updates.txt similarity index 100% rename from source/crud/builders/updates.txt rename to source/builders/updates.txt diff --git a/source/connection/connection-troubleshooting.txt b/source/connection/connection-troubleshooting.txt index d678ae409..5aee84cb4 100644 --- a/source/connection/connection-troubleshooting.txt +++ b/source/connection/connection-troubleshooting.txt @@ -158,6 +158,11 @@ Connection Troubleshooting .. _java-troubleshooting-connection-string-auth: + .. replacement:: connection-pools-learn-more + + To learn more about how connection pooling works in the driver, see the + :ref:`Connection Pools ` page. + .. _java-connection-certificate: Security Certificate Errors diff --git a/source/connection/mongoclient.txt b/source/connection/mongoclient.txt index e280a1f9f..b3d8ddd7b 100644 --- a/source/connection/mongoclient.txt +++ b/source/connection/mongoclient.txt @@ -32,9 +32,51 @@ MongoClient ----------- You can connect to and communicate with MongoDB using the ``MongoClient`` -class. +class. To create a `MongoClientSettings +<{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.html>`__ object, use the ``MongoClientSettings.builder()`` method and chain methods to specify your +settings. After chaining them, use the ``build()`` method to create the +``MongoClientSettings`` object. -Use the ``MongoClients.create()`` method to construct a ``MongoClient``. +To learn about the different settings you can use to control the behavior of your ``MongoClient``, see the :ref:`Specify MongoClient Settings ` guide. + +Example +~~~~~~~ + +This example demonstrates specifying a ``ConnectionString``: + +.. literalinclude:: /includes/fundamentals/code-snippets/MCSettings.java + :start-after: begin ConnectionString + :end-before: end ConnectionString + :language: java + :emphasize-lines: 3 + :dedent: + +.. note:: Chain Order + + Some options in the settings map to a connection string option. + If you specify the same options in your settings and connection + string, the order you chain them determines which option the driver + uses. The driver uses the **last** setting it reads. + + For example, this snippet contains settings with the following times + for the driver to connect to an available socket: + + - The connection string specifies within ``2 SECONDS`` + - The :ref:`socket settings ` specifies within + ``5 SECONDS`` + + .. code-block:: java + :emphasize-lines: 2,4 + + MongoClient mongoClient = MongoClients.create( + MongoClientSettings.builder().applyConnectionString(new ConnectionString("mongodb+srv://:@:/?connectTimeoutMS=2000")) + .applyToSocketSettings(builder -> + builder.connectTimeout(5L, SECONDS)) + .build()); + + Because the driver reads the socket settings options last, the driver + expects to connect to an available socket within ``5 SECONDS`` before + timing out. .. important:: Reuse Your Client @@ -44,10 +86,6 @@ Use the ``MongoClients.create()`` method to construct a ``MongoClient``. All resource usage limits, such as max connections, apply to individual ``MongoClient`` instances. -To learn about the different settings you can use to control the -behavior of your ``MongoClient``, see the guide on -:ref:`MongoClient Settings `. - .. tip:: Always call ``MongoClient.close()`` to clean up resources when an @@ -96,7 +134,7 @@ Replace these values to refer to your MongoDB instance. The last part of the connection URI contains connection options as parameters. In the example, you set two connection options: ``maxPoolSize=20`` and ``w=majority``. For more information about connection options, skip to the -:ref:`connection-options` section of this guide. +:ref:`java-specify-connection-options` section of this guide. .. _connection-uri-srv: diff --git a/source/connection/specify-connection-options.txt b/source/connection/specify-connection-options.txt index c9b63fdbc..624773a4c 100644 --- a/source/connection/specify-connection-options.txt +++ b/source/connection/specify-connection-options.txt @@ -1,18 +1,16 @@ .. _java-specify-connection-options: +.. _connection-options: +.. _specify-mongoclient-settings: ========================== Specify Connection Options ========================== -.. toctree:: - - MongoClient Settings - Connection URI Options - Stable API - Network Compression - JNDI Datasource - AWS Lambda - Connection Security Settings +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol .. facet:: :name: genre @@ -21,11 +19,48 @@ Specify Connection Options .. meta:: :keywords: connection string, URI, Atlas, code example +.. toctree:: + + Stable API + Connection Pools + Cluster Settings + Server Settings + Socket Settings + Configure Client-level CRUD Settings + Network Compression + JNDI Datasource + AWS Lambda + +Overview +-------- + +This section describes the MongoDB connection and authentication options +available in the {+driver-short+}. You can specify the following connection options: -- :ref:`MongoClient Settings ` -- :ref:`Connection URI Options ` - :ref:`Stable API ` -- :ref:`Network Compression ` +- :ref:`Connection Pools ` +- :ref:`Cluster Settings ` +- :ref:`Server Settings ` +- :ref:`Socket Settings ` +- :ref:`Configure Client-level CRUD Settings ` +- :ref:`Network Compression ` - :ref:`JNDI Datasource ` - `AWS Lambda `__ -- :ref:`Connection Security Options ` \ No newline at end of file + +Security and Authentication +--------------------------- + +MongoDB supports many options for securing your data before and during +transportation. For information about security options, see the :ref:`Security +section `, which includes the following pages: + +.. include:: /includes/security/security-pages.rst + +Logging and Monitoring +---------------------- + +You can learn how to using logging and monitoring with the {+driver-short+} in +the :ref:`Logging and Monitoring section `, which +includes the following pages: + +.. include:: /includes/logging-monitoring/logging-monitoring-pages.rst \ No newline at end of file diff --git a/source/connection/specify-connection-options/cluster-settings.txt b/source/connection/specify-connection-options/cluster-settings.txt new file mode 100644 index 000000000..e7b09d625 --- /dev/null +++ b/source/connection/specify-connection-options/cluster-settings.txt @@ -0,0 +1,198 @@ +.. _mcs-cluster-settings: + +================ +Cluster Settings +================ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: timeout, replica set + +Overview +-------- + +In this guide, you can learn about how the {+driver-short+} manages clusters. + +You can specify settings for your clusters by using either a :ref:`connection +string ` or by passing a ``MongoClientSettings`` object to the +:ref:`MongoClient ` constructor. Select the :guilabel:`Connection +String` or :guilabel:`MongoClientSettings` tab to see the options available: + + +.. tabs:: + + .. tab:: Connection String + :tabid: uri + + Include the following parameters in your connection string to modify the driver's behavior when interacting with your MongoDB cluster: + + .. list-table:: + :header-rows: 1 + :widths: 25,20,60 + + * - Option Name + - Type + - Description + + * - ``serverSelectionTimeoutMS`` + - integer + - Specifies the maximum amount of time, in milliseconds, the driver + waits for server selection to succeed before throwing an + exception. + + *Default*: ``30000`` (30 seconds) + + * - ``localThresholdMS`` + - integer + - When communicating with multiple instances of MongoDB in a replica + set, the driver sends requests only to a server whose response + time is less than or equal to the server with the fastest response + time plus the local threshold, in milliseconds. + + *Default*: ``15`` + * - ``replicaSet`` + - string + - Specifies that the :ref:`connection string ` + provided includes multiple hosts. When specified, the driver + attempts to find all members of that set. + + *Default*: ``null`` + + * - ``directConnection`` + - boolean + - Specifies that the driver must connect to the host directly. This + maps to applying ``mode(ClusterConnectionMode.SINGLE)`` to your + ``MongoClientSettings``. + + *Default*: ``false`` + + * - ``srvServiceName`` + - string + - Specifies the service name of the `SRV resource records + `__ the driver retrieves to + construct your :manual:`seed list + `. You must use the + :manual:`DNS Seed List Connection Format + ` in + your :ref:`connection URI ` to use this option. + + *Default*: ``mongodb`` + + This example connects the driver directly to a server, + regardless of the type of MongoDB cluster it's a part of: + + .. code-block:: java + + ConnectionString connectionString = "mongodb://:/?directConnection=true" + MongoClient mongoClient = MongoClients.create(connectionString) + + For more information about these parameters, see the `ConnectionString + <{+api+}/apidocs/mongodb-driver-core/com/mongodb/ConnectionString.html>`__ + API documentation. + + .. tab:: MongoClientSettings + :tabid: MongoClient + + Chain the `applyToClusterSettings() + <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html#applyToClusterSettings(com.mongodb.Block)>`__ + method to modify the driver's behavior when interacting with your MongoDB + cluster. + + The following table describes the methods you can chain to your + settings to modify the driver's behavior: + + .. list-table:: + :header-rows: 1 + :stub-columns: 1 + :widths: 40 60 + + * - Method + - Description + + * - ``addClusterListener()`` + - Adds a listener for cluster-related events. + + * - ``applyConnectionString()`` + - Uses the settings from a ``ConnectionString`` object. + + * - ``applySettings()`` + - Uses the cluster settings specified in a ``ClusterSettings`` object. + + * - ``hosts()`` + - Sets all the specified locations of a Mongo deployment. + + * - ``localThreshold()`` + - Sets the amount of time that a server’s round trip can take and + still be eligible for server selection. + + *Default*: ``15 milliseconds`` + + * - ``mode()`` + - Sets how to connect to a MongoDB deployment. + + * - ``requiredClusterType()`` + - Sets the type of cluster required for the cluster. + + * - ``requiredReplicaSetName()`` + - Sets the replica set name required for the cluster. + + * - ``serverSelectionTimeout()`` + - Sets the maximum time to select a primary node before throwing a + timeout exception. + + *Default*: ``30 seconds`` + + * - ``serverSelector()`` + - Adds a server selector to apply before server selection. + + * - ``srvHost()`` + - Sets the host name to use to look up an SRV DNS record to find the MongoDB hosts. + + If you want to enable the processing of TXT records associated with the host, specify the SRV host in the connection string using the ``applyConnectionString()`` method. + + For example: + + .. code-block:: java + :emphasize-lines: 3 + + MongoClient mongoClient = + MongoClients.create(MongoClientSettings.builder() + .applyConnectionString(new ConnectionString("mongodb+srv://host1.acme.com"))) + + * - ``srvMaxHosts()`` + - Sets the maximum number of hosts the driver can connect to when + using the DNS seedlist (SRV) connection protocol, identified by + the ``mongodb+srv`` connection string prefix. + + Throws an exception if you are not using the SRV connection protocol. + + This example connects the driver directly to a server, + regardless of the type of MongoDB cluster it's a part of: + + .. literalinclude:: /includes/fundamentals/code-snippets/MCSettings.java + :start-after: begin ClusterSettings + :end-before: end ClusterSettings + :language: java + :emphasize-lines: 3-4 + :dedent: + + .. tip:: + + This is analogous to the ``directConnection`` parameter you can specify + in your connection URI. See the Connection String tab for more + information. + + For more information about the chained methods, see the `MongoClientSettings.Builder + <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html>`__ + API documentation. + + \ No newline at end of file diff --git a/source/connection/specify-connection-options/configure-crud.txt b/source/connection/specify-connection-options/configure-crud.txt new file mode 100644 index 000000000..c613920a0 --- /dev/null +++ b/source/connection/specify-connection-options/configure-crud.txt @@ -0,0 +1,196 @@ +.. _configure-client-crud: + +==================================== +Configure Client-level CRUD Settings +==================================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: retries + +Overview +-------- + +In this guide, you can learn about how to use the {+driver-short+} to configure CRUD +operations for ``MongoClient`` instances. + +.. include:: /includes/crud/read-write-pref-concerns.rst + +``MongoDatabase`` and ``MongoCollection`` instances inherit their preferences +and concerns from the ``MongoClient`` that accesses them. However, you can apply +custom settings to your databases and collections. For more information, see the +:ref:`Configure Custom CRUD Settings ` page. + +You can specify client-level CRUD settings by using either a :ref:`connection +string ` or by passing a ``MongoClientSettings`` object to the +:ref:`MongoClients ` constructor. Select the :guilabel:`Connection String` or :guilabel:`MongoClientSettings` tab to see the options available: + +.. tabs:: + + .. tab:: Connection String + :tabid: uri + + Include the following parameters in your connection string to modify the + driver's read or write behavior: + + .. list-table:: + :header-rows: 1 + :widths: 25,20,60 + + * - Option Name + - Type + - Description + + * - ``journal`` + - boolean + - Specifies that the driver must wait for the connected MongoDB instance to group commit to the journal file on disk for all writes. + + *Default*: ``false`` + + * - ``w`` + - string or integer + - Specifies the write concern. For more information about values, see + the {+mdb-server+} documentation for the :manual:`w option + `. + + *Default*: ``1`` + + * - ``wtimeoutMS`` + - integer + - Specifies a time limit, in milliseconds, for the write concern. For + more information, see the {+mdb-server+} documentation for the + :manual:`wtimeoutMS option + `. A value of + ``0`` instructs the driver to never time out write operations. + + *Default*: ``0`` + + * - ``readPreference`` + - string + - Specifies the read preference. For more information about values, see + the {+mdb-server+} documentation for the :manual:`readPreference option + `. + + *Default*: ``primary`` + + * - ``readPreferenceTags`` + - string + - Specifies the read preference tags. For more information about + values, see the {+mdb-server+} documentation for the + :manual:`readPreferenceTags option + `. + + *Default*: ``null`` + + * - ``maxStalenessSeconds`` + - integer + - Specifies, in seconds, how stale a secondary can be before the driver + stops communicating with that secondary. The minimum value is either + 90 seconds or the heartbeat frequency plus 10 seconds, whichever is + greater. For more information, see the {+mdb-server+} documentation for the + :manual:`maxStalenessSeconds option + `. Not + providing a parameter or explicitly specifying ``-1`` indicates that + there must be no staleness check for secondaries. + + *Default*: ``-1`` + + * - ``uuidRepresentation`` + - string + - Specifies the UUID representation to use for read and write + operations. For more information, see the driver documentation for + the `MongoClientSettings.getUuidRepresentation() method + <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.html#getUuidRepresentation()>`__. + + *Default*: ``unspecified`` + + * - ``retryWrites`` + - boolean + - Specifies that the driver must retry supported write operations if + they are unable to complete due to a network error. + + *Default*: ``true`` + + * - ``retryReads`` + - boolean + - Specifies that the driver must retry supported read operations if + they are unable to complete due to a network error. + + *Default*: ``true`` + + The following example sets the read preference to read from the nearest + replica set member: + + .. code-block:: java + + ConnectionString connectionString = "mongodb://:/?readPreference=nearest" + MongoClient mongoClient = MongoClients.create(connectionString) + + For more information about these parameters, see the `ConnectionString + <{+api+}/apidocs/mongodb-driver-core/com/mongodb/ConnectionString.html>`__ + API documentation. + + .. tab:: MongoClientSettings + :tabid: MongoClient + + Chain the following methods to your ``MongoClientSettings`` constructor to modify the driver's read/write behavior: + + .. list-table:: + :stub-columns: 1 + :widths: 40 60 + + * - ``readConcern()`` + - Sets the read concern. + :manual:`Server manual page ` + `API documentation <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html#readConcern(com.mongodb.ReadConcern)>`__ + + * - ``readPreference()`` + - Sets the :manual:`read preference ` + + *Default*: ``primary`` + + * - ``retryReads()`` + - Whether the driver performs :manual:`retry reads + ` if a network error occurs. + + *Default*: ``true`` + + * - ``retryWrites()`` + - Whether the driver performs :manual:`retry writes + ` if a network error occurs. + + *Default*: ``true`` + + * - ``uuidRepresentation()`` + - Sets the UUID representation to use when encoding instances of UUID + and decoding BSON binary values with subtype of 3. + + * - ``writeConcern()`` + - Sets the :manual:`write concern `. + + *Default*: ``WriteConcern#ACKNOWLEDGED``. + | For more information about the default value, see :manual:`Implicit Default Write Concern `. + + The following example sets the read preference to read from the nearest + replica set member: + + .. literalinclude:: /includes/fundamentals/code-snippets/MCSettings.java + :start-after: begin ReadConcern + :end-before: end ReadConcern + :language: java + :dedent: + + For more information about these methods, see the `MongoClientSettings.Builder + <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html#>`__ + API documentation. + + \ No newline at end of file diff --git a/source/connection/specify-connection-options/connection-options.txt b/source/connection/specify-connection-options/connection-options.txt deleted file mode 100644 index 2c2d0e862..000000000 --- a/source/connection/specify-connection-options/connection-options.txt +++ /dev/null @@ -1,345 +0,0 @@ -.. _java-connection-uri-options: -.. _connection-options: - -====================== -Connection URI Options -====================== - -This section explains MongoDB connection and authentication options -supported by the {+driver-short+}. You can pass the connection options as -parameters of the connection URI to specify the behavior of the client. - -.. list-table:: - :header-rows: 1 - :widths: 20 10 20 - - * - Option Name - - Type - - Description - - * - **minPoolSize** - - integer - - Specifies the minimum number of connections that must exist at - any moment in a single connection pool. - - | **Default**: ``0`` - - * - **maxPoolSize** - - integer - - Specifies the maximum number of connections that a connection - pool can have at a given time. - - | **Default**: ``100`` - - * - **waitQueueTimeoutMS** - - integer - - Specifies the maximum amount of time, in milliseconds that a - thread can wait for a connection to become available. - - | **Default**: ``120000`` (120 seconds) - - * - **serverSelectionTimeoutMS** - - integer - - Specifies the maximum amount of time, in milliseconds, the driver - will wait for server selection to succeed before throwing an - exception. - - | **Default**: ``30000`` (30 seconds) - - * - **localThresholdMS** - - integer - - When communicating with multiple instances of MongoDB in a replica - set, the driver will only send requests to a server whose - response time is less than or equal to the server with the fastest - response time plus the local threshold, in milliseconds. - - | **Default**: ``15`` - - * - **heartbeatFrequencyMS** - - integer - - Specifies the frequency, in milliseconds that the driver will - wait between attempts to determine the current state of each - server in the cluster. - - | **Default**: ``10000`` (10 seconds) - - * - **replicaSet** - - string - - Specifies that the :ref:`connection string ` - provided includes multiple hosts. When specified, the driver - attempts to find all members of that set. - - | **Default**: ``null`` - - * - **ssl** - - boolean - - Specifies that all communication with MongoDB instances must - use TLS/SSL. Superseded by the **tls** option. - - | **Default**: ``false`` - - * - **tls** - - boolean - - Specifies that all communication with MongoDB instances must - use TLS. Supersedes the **ssl** option. - - | **Default**: ``false`` - - * - **tlsInsecure** - - boolean - - Specifies that the driver must allow invalid hostnames for TLS - connections. Has the same effect as setting - **tlsAllowInvalidHostnames** to ``true``. To configure TLS security - constraints in other ways, use a - :ref:`custom SSLContext `. - - | **Default**: ``false`` - - * - **tlsAllowInvalidHostnames** - - boolean - - Specifies that the driver must allow invalid hostnames in the - certificate for TLS connections. Supersedes - **sslInvalidHostNameAllowed**. - - | **Default**: ``false`` - - * - **connectTimeoutMS** - - integer - - Specifies the maximum amount of time, in milliseconds, the Java - driver waits for a connection to open before timing out. A value of - ``0`` instructs the driver to never time out while waiting for a connection - to open. - - | **Default**: ``10000`` (10 seconds) - - * - **socketTimeoutMS** - - integer - - Specifies the maximum amount of time, in milliseconds, the Java - driver will wait to send or receive a request before timing out. - A value of ``0`` instructs the driver to never time out while waiting - to send or receive a request. - - | **Default**: ``0`` - - * - **maxIdleTimeMS** - - integer - - Specifies the maximum amount of time, in milliseconds, that the driver - allows a pooled connection to idle before closing the - connection. A value of ``0`` indicates that there is no upper bound - on how long the driver allows a pooled connection to be idle. - - | **Default**: ``0`` - - * - **maxLifeTimeMS** - - integer - - Specifies the maximum amount of time, in milliseconds, the Java - driver will continue to use a pooled connection before closing the - connection. A value of ``0`` indicates that there is no upper bound - on how long the driver can keep a pooled connection open. - - | **Default**: ``0`` - - * - **journal** - - boolean - - Specifies that the driver must wait for the connected MongoDB - instance to group commit to the journal file on disk for all writes. - - | **Default**: ``false`` - - * - **w** - - string or integer - - Specifies the write concern. For more information about values, see - the server documentation for the :manual:`w option - `. - - | **Default**: ``1`` - - * - **wtimeoutMS** - - integer - - Specifies a time limit, in milliseconds, for the write concern. For - more information, see the server documentation for the - :manual:`wtimeoutMS option `. - A value of ``0`` instructs the driver to never time out write operations. - - | **Default**: ``0`` - - * - **readPreference** - - string - - Specifies the read preference. For more information about values, see - the server documentation for the - :manual:`readPreference option `. - - | **Default**: ``primary`` - - * - **readPreferenceTags** - - string - - Specifies the read preference tags. For more information about values, see - the server documentation for the - :manual:`readPreferenceTags option `. - - | **Default**: ``null`` - - * - **maxStalenessSeconds** - - integer - - Specifies, in seconds, how stale a secondary can be before the - driver stops communicating with that secondary. The minimum value is - either 90 seconds or the heartbeat frequency plus 10 seconds, whichever - is greater. For more information, see the server documentation for the - :manual:`maxStalenessSeconds option `. - Not providing a parameter or explicitly specifying ``-1`` indicates - that there must be no staleness check for secondaries. - - | **Default**: ``-1`` - - * - **authMechanism** - - string - - Specifies the :ref:`authentication mechanism - ` that the driver uses if a credential - was supplied. - - | **Default**: By default, the client picks the most secure - mechanism available based on the server version. For possible - values, see the server documentation for the - :manual:`authMechanism option - `. - - * - **authSource** - - string - - Specifies the database in which the supplied credentials are validated. - - | **Default**: ``admin`` - - * - **authMechanismProperties** - - string - - Specifies authentication properties for the specified authentication - mechanism as a list of colon-separated properties and values. - For more information, see the server documentation for - the :manual:`authMechanismProperties option - `. - - | **Default**: ``null`` - - * - **appName** - - string - - Specifies the name of the application provided to MongoDB instances - during the connection handshake. Can be used for server logs and - profiling. - - | **Default**: ``null`` - - * - **compressors** - - string - - Specifies one or more compression algorithms that the driver - will attempt to use to compress requests sent to the connected - MongoDB instance. Possible values include: ``zlib``, ``snappy``, - and ``zstd``. - - | **Default**: ``null`` - - * - **zlibCompressionLevel** - - integer - - Specifies the degree of compression that `Zlib `__ - uses to decrease the size of requests to the connected MongoDB - instance. The level can range from ``-1`` to ``9``, with lower values - compressing faster (but resulting in larger requests) and larger values - compressing slower (but resulting in smaller requests). - - | **Default**: ``null`` - - * - **retryWrites** - - boolean - - Specifies that the driver must retry supported write operations - if they are unable to complete due to a network error. - - | **Default**: ``true`` - - - * - **retryReads** - - boolean - - Specifies that the driver must retry supported read operations - if they are unable to complete due to a network error. - - | **Default**: ``true`` - - * - **serverMonitoringMode** - - string - - Specifies which server monitoring protocol the driver uses. When set to - ``auto``, the monitoring mode is determined by the environment in which - the driver is running. The driver uses ``poll`` mode in function-as-a-service - (FaaS) environments and ``stream`` mode in other environments. - - | **Default**: ``auto`` - - * - **uuidRepresentation** - - string - - Specifies the UUID representation to use for read and write - operations. For more information, see the driver documentation - for the - `MongoClientSettings.getUuidRepresentation() method <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.html#getUuidRepresentation()>`__. - - | **Default**: ``unspecified`` - - * - **directConnection** - - boolean - - Specifies that the driver must connect to the host directly. - - | **Default**: ``false`` - - * - **maxConnecting** - - integer - - Specifies the maximum number of connections a pool can establish - concurrently. - - | **Default**: ``2`` - - * - **srvServiceName** - - string - - Specifies the service name of the - `SRV resource records `__ - the driver retrieves to construct your - :manual:`seed list `. - You must use the - :manual:`DNS Seed List Connection Format ` - in your - :ref:`connection URI ` - to use this option. - - | **Default**: ``mongodb`` - - * - **proxyHost** - - string - - Specifies the SOCKS5 proxy IPv4 address, IPv6 address, or hostname. - You must provide this value to connect to a SOCKS5 proxy. - - | To learn how to connect to a SOCKS5 proxy, see the :ref:`Connect to - MongoDB by Using a SOCKS5 Proxy ` guide. - - | **Default**: ``null`` - - * - **proxyPort** - - non-negative integer - - Specifies the TCP port number of the SOCKS5 proxy server. - - | **Default**: ``1080`` when you set ``proxyHost`` - - * - **proxyUsername** - - string - - Specifies the username for authentication to the SOCKS5 proxy server. - The driver ignores ``null`` and empty string values for this setting. - The driver requires that you pass values for both ``proxyUsername`` - and ``proxyPassword`` or that you omit both values. - - | **Default**: ``null`` - - * - **proxyPassword** - - string - - Specifies the password for authentication to the SOCKS5 proxy server. - The driver ignores ``null`` and empty string values for this setting. - The driver requires that you pass values for both ``proxyUsername`` - and ``proxyPassword`` or that you omit both values. - - | **Default**: ``null`` - -For a complete list of options, see the -`ConnectionString <{+api+}/apidocs/mongodb-driver-core/com/mongodb/ConnectionString.html>`__ -API documentation. diff --git a/source/connection/connection-pools.txt b/source/connection/specify-connection-options/connection-pools.txt similarity index 53% rename from source/connection/connection-pools.txt rename to source/connection/specify-connection-options/connection-pools.txt index 26e18b75c..08d4a6ab8 100644 --- a/source/connection/connection-pools.txt +++ b/source/connection/specify-connection-options/connection-pools.txt @@ -1,4 +1,6 @@ .. _java-connection-pools: +.. _connection-pools: +.. _mcs-connectionpool-settings: ================ Connection Pools @@ -51,7 +53,6 @@ You can specify settings for your connection pool using either a connection string or by passing a ``MongoClientSettings`` object to the ``MongoClients.create()`` method. -The following code creates a client with a maximum connection pool size of ``50``. Select the :guilabel:`Connection String` or :guilabel:`MongoClientSettings` tab to see the corresponding syntax: @@ -59,11 +60,6 @@ see the corresponding syntax: .. tab:: Connection String :tabid: uri - - .. code-block:: java - - ConnectionString connectionString = "mongodb://:/?maxPoolSize=50" - MongoClient mongoClient = MongoClients.create(connectionString) The following are connection string settings you can use to configure your connection pool: @@ -114,22 +110,96 @@ see the corresponding syntax: *Default*: ``120000`` (120 seconds) - To learn more about connection string options, see the - :ref:`Connection Options ` - guide. + * - ``maxLifeTimeMS`` + + - Specifies the maximum amount of time, in milliseconds, the Java driver + will continue to use a pooled connection before closing the + connection. A value of ``0`` indicates that there is no upper bound on + how long the driver can keep a pooled connection open. + + *Default*: ``0`` + + The following code creates a client with a maximum connection pool size of ``50``. + + .. code-block:: java + + ConnectionString connectionString = "mongodb://:/?maxPoolSize=50" + MongoClient mongoClient = MongoClients.create(connectionString) + + For more information about these parameters, see the `ConnectionString + <{+api+}/apidocs/mongodb-driver-core/com/mongodb/ConnectionString.html>`__ + API documentation. .. tab:: MongoClientSettings - :tabid: MongoClient + :tabid: MongoClient + + Chain the `applyToConnectionPoolSettings() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html#applyToConnectionPoolSettings(com.mongodb.Block)>`__ method to modify the way the driver manages its connection pool. + + The following table describes the methods you can chain to your settings to modify the driver's behavior: - .. literalinclude:: /includes/fundamentals/code-snippets/ConnectionPool.java - :start-after: begin MongoSettings - :end-before: end MongoSettings - :language: java - :dedent: + .. list-table:: + :widths: 40 60 + :header-rows: 1 + + * - Method + - Description + + * - ``addConnectionPoolListener()`` + - Adds a listener for connection pool-related events. + + * - ``applyConnectionString()`` + - Uses the settings from a ``ConnectionString`` object. + + * - ``applySettings()`` + - Uses the connection pool settings specified in a + ``ConnectionPoolSettings`` object. + + * - ``maintenanceFrequency()`` + - Sets the frequency for running a maintenance job. + + * - ``maintenanceInitialDelay()`` + - Sets the time to wait before running the first maintenance job. + + * - ``maxConnectionIdleTime()`` + - Sets the maximum time a connection can be idle before it's closed. + + * - ``maxConnectionLifeTime()`` + - Sets the maximum time a pooled connection can be alive before it's + closed. + + * - ``maxSize()`` + - Sets the maximum number of connections associated with a connection + pool. + + *Default*: ``100`` + + * - ``maxWaitTime()`` + - Sets the maximum time to wait for an available connection. + + *Default*: ``2 minutes`` + + * - ``minSize()`` + - Sets the minimum number of connections associated with a connection + pool. + + *Default*: ``0`` + + .. note:: + + This ``maxSize`` and ``minSize`` settings apply to each server in the cluster you connect the driver to. + + For example, assume you connect the driver to a cluster with three + ``mongos`` servers. This means that there can be at most ``maxSize`` + connections and at least ``minSize`` connections to each ``mongos`` + server. + + The following example chains the ``applyToConnectionPoolSettings()`` method to set the thread to wait at most ``10 SECONDS`` for an available connection, and the ``maxSize`` of the connection pool to 200: - For more information on configuring you connection pool by using a - ``MongoClientSettings`` object see the Connection Pool Settings section - of the :ref:`` guide. + .. literalinclude:: /includes/fundamentals/code-snippets/ConnectionPool.java + :start-after: begin MongoSettings + :end-before: end MongoSettings + :language: java + :dedent: Additional Information ---------------------- diff --git a/source/connection/specify-connection-options/mongoclientsettings.txt b/source/connection/specify-connection-options/mongoclientsettings.txt deleted file mode 100644 index f6be3284c..000000000 --- a/source/connection/specify-connection-options/mongoclientsettings.txt +++ /dev/null @@ -1,601 +0,0 @@ -.. _mongoclientsettings: -.. _specify-mongoclient-settings: - -============================ -Specify MongoClient Settings -============================ - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: java sync, customize, connection, code example - -.. contents:: On this page - :local: - :backlinks: none - :depth: 1 - :class: singlecol - -Overview --------- - -In this guide, you can learn about the different settings to control -the behavior of your ``MongoClient``. - -The following sections describe commonly used settings: - -- :ref:`MongoClient Settings ` -- :ref:`Cluster Settings ` -- :ref:`Socket Settings ` -- :ref:`Connection Pool Settings ` -- :ref:`Server Settings ` -- :ref:`TLS/SSL Settings ` - -.. _mcs-settings: - -MongoClient Settings --------------------- - -You can control the behavior of your ``MongoClient`` by creating and passing -in a `MongoClientSettings <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.html>`__ -object to the `MongoClients.create() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoClients.html#create(com.mongodb.MongoClientSettings)>`__ -method. - -To create a ``MongoClientSettings`` object, use the -``MongoClientSettings.builder()`` method and chain methods to specify your -settings. After chaining them, use the ``build()`` method to create the -``MongoClientSettings`` object. - -The following table describes the methods you can chain to modify your -connection behavior: - -.. list-table:: - :widths: 40 60 - :header-rows: 1 - - * - Method - - Description - - * - ``addCommandListener()`` - - Adds a listener for :ref:`command events `. - - * - ``applicationName()`` - - Sets the logical name of the application using the ``MongoClient``. - - * - ``applyConnectionString()`` - - Applies the settings from the given ``ConnectionString`` to the - builder. If you omit this method, the driver attempts to connect to - ``localhost``. - - * - ``applyToClusterSettings()`` - - Applies the ``ClusterSettings.Builder`` block and then sets the - :ref:`cluster settings `. - - * - ``applyToConnectionPoolSettings()`` - - Applies the ``ConnectionPoolSettings.Builder`` block and then sets the - :ref:`connection pool settings `. - - * - ``applyToLoggerSettings()`` - - Applies the ``LoggerSettings.Builder`` block and then sets the - :ref:`logger settings `. - - * - ``applyToServerSettings()`` - - Applies the ``ServerSettings.Builder`` block and then sets the - :ref:`server settings `. - - * - ``applyToSocketSettings()`` - - Applies the ``SocketSettings.Builder`` block and then sets the - :ref:`socket settings `. - - * - ``applyToSslSettings()`` - - Applies the ``SslSettings.Builder`` block and then sets the - :ref:`TLS/SSL settings `. - - * - ``autoEncryptionSettings()`` - - | Sets the :ref:`auto-encryption settings `. - | - | If you omit ``keyVaultClient`` or set - ``bypassAutomaticEncryption`` to false in your - ``AutoEncryptionSettings``, the driver creates a separate, - internal ``MongoClient``. - | - | The internal ``MongoClient`` configuration differs from the - parent ``MongoClient`` by setting the ``minPoolSize`` to 0 and - omitting the ``AutoEncryptionSettings``. - - * - ``codecRegistry()`` - - Sets the :ref:`codec registry `. - - * - ``commandListenerList()`` - - Sets the :ref:`command listeners `. - - * - ``compressorList()`` - - Sets the :ref:`compressors ` to use for compressing - messages to the server. - - * - ``credential()`` - - Sets the :ref:`credential `. - - * - ``readConcern()`` - - Sets the :manual:`read concern `. - - * - ``readPreference()`` - - | Sets the :manual:`read preference `. - | - | **Default**: ``primary`` - - * - ``retryReads()`` - - | Whether the driver performs :manual:`retry reads ` - if a network error occurs. - | - | **Default**: ``true`` - - * - ``retryWrites()`` - - | Whether the driver performs :manual:`retry writes ` - if a network error occurs. - | - | **Default**: ``true`` - - * - ``serverApi()`` - - Sets the :ref:`server API ` to use when sending - commands to the server. - - * - ``transportSettings()`` - - Sets `TransportSettings <{+api+}/apidocs/mongodb-driver-core/com/mongodb/connection/TransportSettings.html>`__. - - * - ``uuidRepresentation()`` - - Sets the UUID representation to use when encoding instances of UUID - and decoding BSON binary values with subtype of 3. - - * - ``writeConcern()`` - - | Sets the :manual:`write concern `. - | - | **Default**: ``WriteConcern#ACKNOWLEDGED``. For more information about - the default value, see :manual:`Implicit Default Write Concern `. - -.. _connection-string-example: - -Example -~~~~~~~ - -This example demonstrates specifying a ``ConnectionString``: - -.. literalinclude:: /includes/fundamentals/code-snippets/MCSettings.java - :start-after: begin ConnectionString - :end-before: end ConnectionString - :language: java - :emphasize-lines: 3 - :dedent: - -.. note:: Chain Order - - Some options in the settings map to a connection string option. - If you specify the same options in your settings and connection - string, the order you chain them determines which option the driver - uses. The driver uses the **last** setting it reads. - - For example, this snippet contains settings with the following times - for the driver to connect to an available socket: - - - The connection string specifies within ``2 SECONDS`` - - The :ref:`socket settings ` specifies within - ``5 SECONDS`` - - .. code-block:: java - :emphasize-lines: 2,4 - - MongoClient mongoClient = MongoClients.create( - MongoClientSettings.builder().applyConnectionString(new ConnectionString("mongodb+srv://:@:/?connectTimeoutMS=2000")) - .applyToSocketSettings(builder -> - builder.connectTimeout(5L, SECONDS)) - .build()); - - Since the driver reads the socket settings options last, the driver - expects to connect to an available socket within ``5 SECONDS`` before - timing out. - -.. tip:: Log Your Settings - - To log the ``MongoClient`` instance settings, - set the ``org.mongodb.driver.client`` named - logger to the ``INFO`` level. - - To learn more about logging with the {+driver-long+}, see the - :ref:`java-fundamentals-logging` guide. - -.. _mcs-cluster-settings: - -Cluster Settings ----------------- - -Chain the `applyToClusterSettings() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html#applyToClusterSettings(com.mongodb.Block)>`__ -method to modify the driver's behavior when interacting with your -MongoDB cluster. - -The following table describes the methods you can chain to your -settings to modify the driver's behavior: - -.. list-table:: - :widths: 40 60 - :header-rows: 1 - - * - Method - - Description - - * - ``addClusterListener()`` - - Adds a listener for cluster-related events. - - * - ``applyConnectionString()`` - - Uses the settings from a ``ConnectionString`` object. - - * - ``applySettings()`` - - Uses the cluster settings specified in a ``ClusterSettings`` object. - - * - ``hosts()`` - - Sets all the specified locations of a Mongo deployment. - - * - ``localThreshold()`` - - | Sets the amount of time that a server’s round trip can take and still - be eligible for server selection. - | - | **Default**: ``15 milliseconds`` - - * - ``mode()`` - - Sets how to connect to a MongoDB deployment. - - * - ``requiredClusterType()`` - - Sets the type of cluster required for the cluster. - - * - ``requiredReplicaSetName()`` - - Sets the replica set name required for the cluster. - - * - ``serverSelectionTimeout()`` - - | Sets the maximum time to select a primary node before throwing a - timeout exception. - | - | **Default**: ``30 seconds`` - - * - ``serverSelector()`` - - Adds a server selector to apply before server selection. - - * - ``srvHost()`` - - | Sets the host name to use to look up an SRV DNS record to find the - MongoDB hosts. - | - | If you want to enable the processing of TXT records associated with the host, - specify the SRV host in the connection string - using the ``applyConnectionString()`` method. - | - | For example: - - .. code-block:: java - :emphasize-lines: 3 - - MongoClient mongoClient = - MongoClients.create(MongoClientSettings.builder() - .applyConnectionString(new ConnectionString("mongodb+srv://host1.acme.com"))) - - * - ``srvMaxHosts()`` - - | Sets the maximum number of hosts the driver can connect to when using - the DNS seedlist (SRV) connection protocol, identified by the - ``mongodb+srv`` connection string prefix. - | - | Throws an exception if you are not using the SRV connection protocol. - -Example -~~~~~~~ - -This example specifies for the driver to connect directly to a server, -regardless of the type of MongoDB cluster it's a part of: - -.. literalinclude:: /includes/fundamentals/code-snippets/MCSettings.java - :start-after: begin ClusterSettings - :end-before: end ClusterSettings - :language: java - :emphasize-lines: 3-4 - :dedent: - -.. tip:: - - This is analogous to the ``directConnection`` parameter you can specify - in your connection URI. See :ref:`` for more - information. - -.. _mcs-connectionpool-settings: - -Connection Pool Settings ------------------------- - -Chain the `applyToConnectionPoolSettings() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html#applyToConnectionPoolSettings(com.mongodb.Block)>`__ -method to modify the way the driver manages its connection pool. - -The following table describes the methods you can chain to your -settings to modify the driver's behavior: - -.. list-table:: - :widths: 40 60 - :header-rows: 1 - - * - Method - - Description - - * - ``addConnectionPoolListener()`` - - Adds a listener for connection pool-related events. - - * - ``applyConnectionString()`` - - Uses the settings from a ``ConnectionString`` object. - - * - ``applySettings()`` - - Uses the connection pool settings specified in a - ``ConnectionPoolSettings`` object. - - * - ``maintenanceFrequency()`` - - Sets the frequency for running a maintenance job. - - * - ``maintenanceInitialDelay()`` - - Sets the time to wait before running the first maintenance job. - - * - ``maxConnectionIdleTime()`` - - Sets the maximum time a connection can be idle before it's closed. - - * - ``maxConnectionLifeTime()`` - - Sets the maximum time a pooled connection can be alive before it's - closed. - - * - ``maxSize()`` - - | Sets the maximum number of connections associated with a connection - pool. - | - | **Default**: ``100`` - - * - ``maxWaitTime()`` - - | Sets the maximum time to wait for an available connection. - | - | **Default**: ``2 minutes`` - - * - ``minSize()`` - - | Sets the minimum number of connections associated with a connection - pool. - | - | **Default**: ``0`` - - -.. note:: - - This ``maxSize`` and ``minSize`` settings apply to each server - in the cluster you connect the driver to. - - For example, assume you connect the driver to a cluster with three - ``mongos`` servers. This means that there can be at most ``maxSize`` - connections and at least ``minSize`` connections to each ``mongos`` server. - -Example -~~~~~~~ - -This example specifies the following driver behavior in a pool of -``Connection`` types: - -- The thread to wait at most ``10 SECONDS`` for an available connection -- To have at most ``200`` connections associated with the pool - -.. literalinclude:: /includes/fundamentals/code-snippets/MCSettings.java - :start-after: begin ConnectionPoolSettings - :end-before: end ConnectionPoolSettings - :language: java - :emphasize-lines: 3-5 - :dedent: - -.. _mcs-logger-settings: - -Logger Settings ---------------- - -Chain the `applyToLoggerSettings() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html#applyToLoggerSettings(com.mongodb.Block)>`__ -method to modify the logging behavior of the driver. - -The following table describes the methods you can chain to your -settings to modify the logging behavior: - -.. list-table:: - :widths: 40 60 - :header-rows: 1 - - * - Method - - Description - - * - ``maxDocumentLength()`` - - | Sets the maximum document length, in characters, of a single log - message. - | - | **Default**: ``1000`` - -Example -~~~~~~~ - -This example specifies that the maximum number of characters for a single log -message is set to ``5000`` characters. - -.. literalinclude:: /includes/fundamentals/code-snippets/MCSettings.java - :start-after: begin LoggerSettings - :end-before: end LoggerSettings - :language: java - :emphasize-lines: 3-4 - :dedent: - -.. _mcs-server-settings: - -Server Settings ---------------- - -Chain the `applyToServerSettings() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html#applyToServerSettings(com.mongodb.Block)>`__ -method to modify the driver's behavior when monitoring each MongoDB -deployment. - -The following table describes the methods you can chain to your -settings to modify the driver's behavior: - -.. list-table:: - :widths: 40 60 - :header-rows: 1 - - * - Method - - Description - - * - ``addServerListener()`` - - Adds a listener for server-related events. - - * - ``addServerMonitorListener()`` - - Adds a listener for server monitor-related events. - - * - ``applyConnectionString()`` - - Uses the settings from a ``ConnectionString`` object. - - * - ``applySettings()`` - - Uses the server settings specified in a ``ServerSettings`` object. - - * - ``heartbeatFrequency()`` - - | Sets the interval for a cluster monitor to attempt reaching a server. - | - | **Default**: ``10 seconds`` - - * - ``minHeartbeatFrequency()`` - - | Sets the minimum interval for server monitoring checks. - | - | **Default**: ``500 milliseconds`` - -Example -~~~~~~~ - -This example specifies the following driver behavior in a MongoDB deployment: - -- The minimum interval for server monitoring checks to be at least - ``700 MILLISECONDS`` -- The cluster monitor to attempt reaching a server every ``15 SECONDS`` - -.. literalinclude:: /includes/fundamentals/code-snippets/MCSettings.java - :start-after: begin ServerSettings - :end-before: end ServerSettings - :language: java - :emphasize-lines: 3-5 - :dedent: - -.. _mcs-socket-settings: - -Socket Settings ---------------- - -Chain the `applyToSocketSettings() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html#applyToSocketSettings(com.mongodb.Block)>`__ -method to modify the driver's behavior when connecting and communicating -with your MongoDB deployment. - -The following table describes the methods you can chain to your settings -to modify the driver's behavior: - -.. list-table:: - :widths: 40 60 - :header-rows: 1 - - * - Method - - Description - - * - ``applyConnectionString()`` - - Uses the settings from a ``ConnectionString`` object. - - * - ``applySettings()`` - - Uses the socket settings specified in a ``SocketSettings`` object. - - * - ``connectTimeout()`` - - | Sets the maximum time to connect to an available socket before throwing - a timeout exception. - | - | **Default**: ``10 seconds`` - - * - ``readTimeout()`` - - | Sets the maximum time to read from an available socket before throwing a - timeout exception. - | - | **Default**: ``0``, which indicates no timeout - - * - ``receiveBufferSize()`` - - | Sets the socket's buffer size when receiving. - | - | **Default**: The operating system default - - * - ``sendBufferSize()`` - - | Sets the socket's buffer size when sending. - | - | **Default**: The operating system default - -.. note:: Connect to MongoDB by using a SOCKS5 Proxy - - You can chain the ``applyToProxySettings()`` method to your socket settings to - connect to MongoDB by using a SOCKS5 proxy. To learn how to use a SOCKS5 proxy - and set proxy settings, see the :ref:`Connect to MongoDB by Using a SOCKS5 Proxy - ` guide. - -.. _java-socketsettings-example: - -Example -~~~~~~~ - -This example specifies the following driver behavior in a MongoDB socket: - -- To connect to an available socket within ``10 SECONDS`` -- To read from an available socket within ``15 SECONDS`` - -.. literalinclude:: /includes/fundamentals/code-snippets/MCSettings.java - :start-after: begin SocketSettings - :end-before: end SocketSettings - :language: java - :emphasize-lines: 3-5 - :dedent: - -.. _mcs-ssl-settings: - -TLS/SSL Settings ----------------- - -Chain the `applyToSslSettings() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html#applyToSslSettings(com.mongodb.Block)>`__ -method to modify the driver's behavior when using TLS/SSL to secure a -connection between your application and MongoDB. - -The following table describes the methods you can chain to your -settings to modify the driver's behavior: - -.. list-table:: - :widths: 40 60 - :header-rows: 1 - - * - Method - - Description - - * - ``applyConnectionString()`` - - Uses the settings from a ``ConnectionString`` object. - - * - ``applySettings()`` - - Uses the TLS/SSL settings specified in a ``SslSettings`` object. - - * - ``context()`` - - Sets the ``SSLContext`` for use when you enable TLS/SSL. - - * - ``enabled()`` - - Whether to enable TLS/SSL. (You must enable this for Atlas clusters.) - - * - ``invalidHostNameAllowed()`` - - Whether to allow a mismatch between the server’s hostname and the - hostname specified by the TLS certificate. - -Example -~~~~~~~ - -This example specifies for the driver to enable TLS/SSL when connecting -to MongoDB: - -.. literalinclude:: /includes/fundamentals/code-snippets/MCSettings.java - :start-after: begin SslSettings - :end-before: end SslSettings - :language: java - :emphasize-lines: 3-4 - :dedent: \ No newline at end of file diff --git a/source/connection/specify-connection-options/network-compression.txt b/source/connection/specify-connection-options/network-compression.txt index 34b71badd..dd50f656a 100644 --- a/source/connection/specify-connection-options/network-compression.txt +++ b/source/connection/specify-connection-options/network-compression.txt @@ -56,27 +56,78 @@ by specifying the algorithms in one of the following ways: - Use the ``compressors`` parameter in your connection string. - Chain the ``compressorList()`` method to the ``MongoClientSettings.builder()`` method. -This example shows how to specify the Snappy, Zstandard, and Zlib compression -algorithms. Select the :guilabel:`Connection String` or :guilabel:`MongoClientSettings` +Select the :guilabel:`Connection String` or :guilabel:`MongoClientSettings` tab to see the corresponding syntax: .. tabs:: - .. tab:: Connection String - :tabid: connectionstring - - .. literalinclude:: /includes/connect/NetworkCompression.java - :start-after: start-specify-connection-string - :end-before: end-specify-connection-string - :language: java - - .. tab:: MongoClientSettings - :tabid: mongoclientsettings - - .. literalinclude:: /includes/connect/NetworkCompression.java - :start-after: start-specify-client-settings - :end-before: end-specify-client-settings - :language: java + .. tab:: Connection String + :tabid: uri + + Include the following parameters in your connection string to enable compression: + + .. list-table:: + :header-rows: 1 + :widths: 25,20,60 + + * - Option Name + - Type + - Description + + * - ``compressors`` + - string + - Specifies one or more compression algorithms that the driver will + attempt to use to compress requests sent to the connected MongoDB + instance. Possible values include: ``zlib``, ``snappy``, and + ``zstd``. + + *Default*: ``null`` + + * - ``zlibCompressionLevel`` + - integer + - Specifies the degree of compression that `Zlib `__ + uses to decrease the size of requests to the connected MongoDB + instance. The level can range from ``-1`` to ``9``, with lower values + compressing faster (but resulting in larger requests) and larger + values compressing slower (but resulting in smaller requests). + + *Default*: ``null`` + + The following specifies the order in which the driver will attempt to + compress requests before they are sent: + + .. literalinclude:: /includes/connect/NetworkCompression.java + :start-after: start-specify-connection-string + :end-before: end-specify-connection-string + :language: java + + For more information about these parameters, see the `ConnectionString + <{+api+}/apidocs/mongodb-driver-core/com/mongodb/ConnectionString.html>`__ + API documentation. + + .. tab:: MongoClientSettings + :tabid: mongoclientsettings + + Chain the following methods to your ``MongoClientSettings`` constructor to modify the driver's compression behavior: + + .. list-table:: + :widths: 40 60 + :header-rows: 1 + + * - Method + - Description + + * - ``compressorList()`` + - Sets the compressors to use for compressing messages to the server. + + .. literalinclude:: /includes/connect/NetworkCompression.java + :start-after: start-specify-client-settings + :end-before: end-specify-client-settings + :language: java + + For more information about the chained methods, see the `MongoClientSettings.Builder + <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html>`__ + API documentation. .. _java-compression-dependencies: diff --git a/source/connection/specify-connection-options/server-settings.txt b/source/connection/specify-connection-options/server-settings.txt new file mode 100644 index 000000000..5a8e76929 --- /dev/null +++ b/source/connection/specify-connection-options/server-settings.txt @@ -0,0 +1,132 @@ +.. _mcs-server-settings: + +=============== +Server Settings +=============== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +Overview +-------- + +In this guide, you can learn about how the {+driver-short+} manages server +settings. + +Configuring Server Settings +--------------------------- + +.. tabs:: + + .. tab:: Connection String + :tabid: uri + + Include the following parameters in your connection string to modify the + driver's behavior when interacting with the server: + + .. list-table:: + :header-rows: 1 + :widths: 25,20,60 + + * - Option Name + - Type + - Description + + * - ``appName`` + - string + - Specifies the name of the application provided to MongoDB instances + during the connection handshake. Can be used for server logs and + profiling. + + *Default*: ``null`` + + * - ``serverMonitoringMode`` + - string + - Specifies which server monitoring protocol the driver uses. When set + to ``auto``, the monitoring mode is determined by the environment in + which the driver is running. The driver uses ``poll`` mode in + function-as-a-service (FaaS) environments and ``stream`` mode in + other environments. + + *Default*: ``auto`` + + * - ``heartbeatFrequencyMS`` + - integer + - Specifies the frequency, in milliseconds that the driver will wait + between attempts to determine the current state of each server in + the cluster. + + *Default*: ``10000`` (10 seconds) + + + This example specifies that the cluster monitor will attempt to reach a + server every 15 seconds: + + .. code-block:: java + + ConnectionString connectionString = "mongodb://:/?heartbeatFrequencyMS=15000" + MongoClient mongoClient = MongoClients.create(connectionString) + + For more information about these parameters, see the `ConnectionString + <{+api+}/apidocs/mongodb-driver-core/com/mongodb/ConnectionString.html>`__ + API documentation. + + + .. tab:: MongoClientSettings + :tabid: MongoClient + + Chain the `applyToServerSettings() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html#applyToServerSettings(com.mongodb.Block)>`__ method to modify the driver's behavior when monitoring each MongoDB deployment. + + The following table describes the methods you can chain to your settings to modify the driver's behavior: + + .. list-table:: + :widths: 40 60 + :header-rows: 1 + + * - Method + - Description + + * - ``addServerListener()`` + - Adds a listener for server-related events. + + * - ``addServerMonitorListener()`` + - Adds a listener for server monitor-related events. + + * - ``applySettings()`` + - Uses the server settings specified in a ``ServerSettings`` object. + + * - ``heartbeatFrequency()`` + - Sets the interval for a cluster monitor to attempt reaching a server. + + *Default*: ``10 seconds`` + + * - ``minHeartbeatFrequency()`` + - Sets the minimum interval for server monitoring checks. + + *Default*: ``500 milliseconds`` + + This example specifies the following driver behavior in a MongoDB deployment: + + - The minimum interval for server monitoring checks to be at least + ``700 MILLISECONDS`` + - The cluster monitor to attempt reaching a server every ``15 SECONDS`` + + .. literalinclude:: /includes/fundamentals/code-snippets/MCSettings.java + :start-after: begin ServerSettings + :end-before: end ServerSettings + :language: java + :emphasize-lines: 3-5 + :dedent: + + For more information about the chained methods, see the `MongoClientSettings.Builder + <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html>`__ + API documentation. + + diff --git a/source/connection/specify-connection-options/socket-settings.txt b/source/connection/specify-connection-options/socket-settings.txt new file mode 100644 index 000000000..77f0ee5af --- /dev/null +++ b/source/connection/specify-connection-options/socket-settings.txt @@ -0,0 +1,140 @@ +.. _mcs-socket-settings: + +=============== +Socket Settings +=============== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +Overview +-------- + +In this guide, you can learn about how the {+driver-short+} manages socket +settings. + +You can specify settings for your sockets by using either a :ref:`connection +string ` or by passing a ``MongoClientSettings`` object to the +:ref:`MongoClients ` constructor. Select the :guilabel:`Connection String` or :guilabel:`MongoClientSettings` tab to see the options available: + +.. tabs:: + + .. tab:: Connection String + :tabid: uri + + .. list-table:: + :header-rows: 1 + :widths: 25,20,60 + + * - Option Name + - Type + - Description + + * - ``connectTimeoutMS`` + - integer + - Specifies the maximum amount of time, in milliseconds, the Java + driver waits for a connection to open before timing out. A value of + ``0`` instructs the driver to never time out while waiting for a + connection to open. + + *Default*: ``10000`` (10 seconds) + + * - ``socketTimeoutMS`` + - integer + - Specifies the maximum amount of time, in milliseconds, the Java + driver will wait to send or receive a request before timing out. A + value of ``0`` instructs the driver to never time out while waiting + to send or receive a request. + + *Default*: ``0`` + + This example specifies that the driver will time out after 15 seconds of + waiting for a connection to open: + + .. code-block:: java + + ConnectionString connectionString = "mongodb://:/?connectTimeoutMS=15000" + MongoClient mongoClient = MongoClients.create(connectionString) + + For more information about these parameters, see the `ConnectionString + <{+api+}/apidocs/mongodb-driver-core/com/mongodb/ConnectionString.html>`__ + API documentation. + + .. tab:: MongoClientSettings + :tabid: MongoClient + + Chain the `applyToSocketSettings() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html#applyToSocketSettings(com.mongodb.Block)>`__ + method to modify the driver's behavior when connecting and communicating + with your MongoDB deployment. + + The following table describes the methods you can chain to your settings + to modify the driver's behavior: + + .. list-table:: + :widths: 40 60 + :header-rows: 1 + + * - Method + - Description + + * - ``applyConnectionString()`` + - Uses the settings from a ``ConnectionString`` object. + + * - ``applySettings()`` + - Uses the socket settings specified in a ``SocketSettings`` object. + + * - ``connectTimeout()`` + - Sets the maximum time to connect to an available socket before throwing + a timeout exception. + + *Default*: ``10 seconds`` + + * - ``readTimeout()`` + - Sets the maximum time to read from an available socket before throwing a + timeout exception. + + *Default*: ``0``, which indicates no timeout + + * - ``receiveBufferSize()`` + - Sets the socket's buffer size when receiving. + + *Default*: The operating system default + + * - ``sendBufferSize()`` + - Sets the socket's buffer size when sending. + + *Default*: The operating system default + + .. note:: Connect to MongoDB by using a SOCKS5 Proxy + + You can chain the ``applyToProxySettings()`` method to your socket settings to + connect to MongoDB by using a SOCKS5 proxy. To learn how to use a SOCKS5 proxy + and set proxy settings, see the :ref:`Connect to MongoDB by Using a SOCKS5 Proxy + ` guide. + + .. _java-socketsettings-example: + + This example specifies the following driver behavior in a MongoDB socket: + + - To connect to an available socket within ``10 SECONDS`` + - To read from an available socket within ``15 SECONDS`` + + .. literalinclude:: /includes/fundamentals/code-snippets/MCSettings.java + :start-after: begin SocketSettings + :end-before: end SocketSettings + :language: java + :emphasize-lines: 3-5 + :dedent: + + For more information about the chained methods, see the `MongoClientSettings.Builder + <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html>`__ + API documentation. + + diff --git a/source/connection/specify-connection-options/stable-api.txt b/source/connection/specify-connection-options/stable-api.txt index f536c5eff..ec9168631 100644 --- a/source/connection/specify-connection-options/stable-api.txt +++ b/source/connection/specify-connection-options/stable-api.txt @@ -122,14 +122,16 @@ described in the following table. - Description * - Strict - - | **Optional**. When set, if you call a command that is not part of the declared API version, the driver raises an exception. - | - | Default: **false** - - * - DeprecationErrors - - | **Optional**. When set, if you call a command that is deprecated in the declared API version, the driver raises an exception. - | - | Default: **false** + - **Optional**. When set, if you call a command that is not part of the + declared API version, the driver raises an exception. + + Default: **false** + + * - DeprecationErrors + - **Optional**. When set, if you call a command that is deprecated in the + declared API version, the driver raises an exception. + + Default: **false** The following example shows how you can set the two options on an instance of ``ServerApi`` by chaining methods on the ``ServerApi.Builder``: diff --git a/source/crud.txt b/source/crud.txt index 3fc0b0fde..8a5f3277e 100644 --- a/source/crud.txt +++ b/source/crud.txt @@ -7,25 +7,14 @@ CRUD Operations .. toctree:: :caption: CRUD Operations - Read - Write - Query + Insert Documents + Query Documents + Update Documents + Replace Documents + Delete Documents + Bulk Operations Compound Operations Transactions - Builders - Aggregation - Aggregation Expressions Collations Large File Storage with GridFS - -CRUD (Create, Read, Update, Delete) operations enable you to work with -data stored in MongoDB. - -- :ref:`Read Operations ` find and return - documents stored in your database. -- :ref:`Write Operations ` insert, modify, - or delete documents in your database. - -Some operations combine aspects of read and write operations. See our -guide on :ref:`compound operations ` -to learn more about these hybrid methods. + Configure Custom CRUD Settings diff --git a/source/crud/write-operations/bulk.txt b/source/crud/bulk.txt similarity index 99% rename from source/crud/write-operations/bulk.txt rename to source/crud/bulk.txt index 8d0ee7e59..f08fcf22d 100644 --- a/source/crud/write-operations/bulk.txt +++ b/source/crud/bulk.txt @@ -1,8 +1,8 @@ .. _java-fundamentals-bulkwrite: -=============== -Bulk Operations -=============== +===================== +Bulk Write Operations +===================== .. contents:: On this page :local: diff --git a/source/crud/crud-settings.txt b/source/crud/crud-settings.txt new file mode 100644 index 000000000..e5c8b0296 --- /dev/null +++ b/source/crud/crud-settings.txt @@ -0,0 +1,50 @@ +.. _java-configure-custom-crud: + +============================== +Configure Custom CRUD Settings +============================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +Overview +-------- + +In this guide, you can learn about how the {+driver-short+} configures CRUD +operations for ``MongoDatabase`` and ``MongoCollection`` instances. + +.. include:: /includes/crud/read-write-pref-concerns.rst + +By default, ``MongoDatabase`` and ``MongoCollection`` instances inherit their preferences +and concerns from the ``MongoClient`` that accesses them. See the +:ref:`Configure Client-level CRUD Settings ` page for +more information. However, you can apply custom settings to your individual databases and +collections by using the following methods: + +- `MongoDatabase.withReadConcern() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoDatabase.html#withReadConcern(com.mongodb.ReadConcern)>`__ + +- `MongoDatabase.withReadPreference() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoDatabase.html#withReadPreference(com.mongodb.ReadPreference)>`__ + +- `MongoDatabase.withWriteConcern() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoDatabase.html#withWriteConcern(com.mongodb.WriteConcern)>`__ + +- `MongoCollection.withReadConcern() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#withReadConcern(com.mongodb.ReadConcern)>`__ + +- `MongoCollection.withReadPreference() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#withReadPreference(com.mongodb.ReadPreference)>`__ + +- `MongoCollection.withWriteConcern() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#withWriteConcern(com.mongodb.WriteConcern)>`__ + +.. tip:: + + The ``withReadConcern()``, ``withReadPreference()``, and + ``withWriteConcern`` methods create a new instance of a + ``MongoDatabase`` or ``MongoCollection`` with the desired preference + or concern. The ``MongoDatabase`` or ``MongoCollection`` upon which + the method is called retains its original preference and concern + settings. \ No newline at end of file diff --git a/source/crud/write-operations/delete.txt b/source/crud/delete.txt similarity index 100% rename from source/crud/write-operations/delete.txt rename to source/crud/delete.txt diff --git a/source/crud/write-operations/insert.txt b/source/crud/insert.txt similarity index 100% rename from source/crud/write-operations/insert.txt rename to source/crud/insert.txt diff --git a/source/crud/query-documents.txt b/source/crud/query-documents.txt new file mode 100644 index 000000000..b416f9759 --- /dev/null +++ b/source/crud/query-documents.txt @@ -0,0 +1,37 @@ +.. _java-read-operations: + +=============== +Query Documents +=============== + +.. meta:: + :description: Learn about the commands for running read operations on MongoDB by using the {+driver-long+}. + +.. toctree:: + :caption: Query Documents + + Specify a Query + Find Documents + Count Documents + Retrieve Distinct Values of a Field + Specify Which Fields to Return + Limit Returned Results + Sort Results + Skip Returned Results + Search Geospatially + Search Text + Access Data from a Cursor + + + +- :ref:`Specify a Query ` +- :ref:`Find Documents ` +- :ref:`Access Data from a Cursor ` +- :ref:`Count Documents ` +- :ref:`Retrieve Distinct Values of a Field ` +- :ref:`Specify Which Fields to Return ` +- :ref:`Limit Returned Results ` +- :ref:`Sort Results ` +- :ref:`Skip Returned Results ` +- :ref:`Search Geospatially ` +- :ref:`Search Text ` diff --git a/source/crud/read-operations/count.txt b/source/crud/query-documents/count.txt similarity index 100% rename from source/crud/read-operations/count.txt rename to source/crud/query-documents/count.txt diff --git a/source/crud/read-operations/cursor.txt b/source/crud/query-documents/cursor.txt similarity index 100% rename from source/crud/read-operations/cursor.txt rename to source/crud/query-documents/cursor.txt diff --git a/source/crud/read-operations/distinct.txt b/source/crud/query-documents/distinct.txt similarity index 100% rename from source/crud/read-operations/distinct.txt rename to source/crud/query-documents/distinct.txt diff --git a/source/crud/read-operations/retrieve.txt b/source/crud/query-documents/find.txt similarity index 96% rename from source/crud/read-operations/retrieve.txt rename to source/crud/query-documents/find.txt index c2de1b09d..a738def52 100644 --- a/source/crud/read-operations/retrieve.txt +++ b/source/crud/query-documents/find.txt @@ -1,11 +1,9 @@ .. _java-fundamentals-retrieve-data: ============== -Retrieve Data +Find Documents ============== - - .. contents:: On this page :local: :backlinks: none @@ -15,10 +13,8 @@ Retrieve Data Overview -------- -In this guide, you can learn how to retrieve data from your MongoDB -database. To retrieve data, use read operations. - -Read operations allow you to do the following: +In this guide, you can learn how to retrieve documents from your MongoDB +database. You can find your documents by using the following: - Retrieve a subset of documents from your collection using a :ref:`find operation ` - Perform transformations on retrieved documents from your collection using an :ref:`aggregate operation ` diff --git a/source/crud/read-operations/geo.txt b/source/crud/query-documents/geo.txt similarity index 100% rename from source/crud/read-operations/geo.txt rename to source/crud/query-documents/geo.txt diff --git a/source/crud/read-operations/limit.txt b/source/crud/query-documents/limit.txt similarity index 100% rename from source/crud/read-operations/limit.txt rename to source/crud/query-documents/limit.txt diff --git a/source/crud/read-operations/project.txt b/source/crud/query-documents/project.txt similarity index 100% rename from source/crud/read-operations/project.txt rename to source/crud/query-documents/project.txt diff --git a/source/crud/read-operations/skip.txt b/source/crud/query-documents/skip.txt similarity index 100% rename from source/crud/read-operations/skip.txt rename to source/crud/query-documents/skip.txt diff --git a/source/crud/read-operations/sort.txt b/source/crud/query-documents/sort.txt similarity index 100% rename from source/crud/read-operations/sort.txt rename to source/crud/query-documents/sort.txt diff --git a/source/crud/query-document.txt b/source/crud/query-documents/specify-query.txt similarity index 100% rename from source/crud/query-document.txt rename to source/crud/query-documents/specify-query.txt diff --git a/source/crud/read-operations/text.txt b/source/crud/query-documents/text.txt similarity index 100% rename from source/crud/read-operations/text.txt rename to source/crud/query-documents/text.txt diff --git a/source/crud/read-operations.txt b/source/crud/read-operations.txt deleted file mode 100644 index 40cd66a08..000000000 --- a/source/crud/read-operations.txt +++ /dev/null @@ -1,33 +0,0 @@ -.. _java-read-operations: - -=============== -Read Operations -=============== - -.. meta:: - :description: Learn about the commands for running read operations on MongoDB by using the {+driver-long+}. - -.. toctree:: - :caption: Read Operations - - Retrieve Data - Access Data from a Cursor - Sort Results - Skip Returned Results - Limit Returned Results - Specify Fields to Return - Count Documents - Retrieve Distinct Values of a Field - Geospatial Data - Search Text - -- :ref:`Retrieve ` -- :ref:`Access Data From a Cursor ` -- :ref:`Sort Results ` -- :ref:`Skip Returned Results ` -- :ref:`Limit the Number of Returned Results ` -- :ref:`Specify Which Fields to Return ` -- :ref:`Count Documents ` -- :ref:`Retrieve Distinct Values of a Field ` -- :ref:`Search Geospatially ` -- :ref:`Search Text ` diff --git a/source/crud/replace-documents.txt b/source/crud/replace-documents.txt new file mode 100644 index 000000000..9785a34c0 --- /dev/null +++ b/source/crud/replace-documents.txt @@ -0,0 +1,123 @@ +.. _java-replace-document: +.. _replace-operation: + +================= +Replace Documents +================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +In this guide, you can learn how to replace documents in a MongoDB +collection. A replace operation specifies the fields and values to replace +a single document from your collection. + +Replace One Method +------------------ + +A replace operation substitutes one document from your collection. The +substitution occurs between a document your query filter matches and a +replacement document. + +The `replaceOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#replaceOne(org.bson.conversions.Bson,TDocument)>`__ +method removes all the existing fields and values in the +matching document (except the ``_id`` field) and substitutes it with the +replacement document. + +You can call the ``replaceOne()`` method on a ``MongoCollection`` +instance as follows: + +.. code-block:: java + + collection.replaceOne(, ); + +Replace Operation Parameters +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The ``replaceOne()`` method has the following parameters: + +- ``query`` specifies a query filter with the criteria to match a + document to replace in your collection. +- ``replacement`` specifies fields and values of a new ``Document`` + object to replace the matched document. +- *(Optional)* ``replaceOptions`` specifies options that you can set to + customize how the driver performs the replace operation. To learn more + about this type, see the API documentation for `ReplaceOptions + <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/ReplaceOptions.html>`__. + +Replace One Example +~~~~~~~~~~~~~~~~~~~ + +In this example, a paint store sells five different +colors of paint. The ``paint_inventory`` collection represents their +current inventory: + +.. code-block:: json + + { "_id": 1, "color": "red", "qty": 5 } + { "_id": 2, "color": "purple", "qty": 8 } + { "_id": 3, "color": "yellow", "qty": 0 } + { "_id": 4, "color": "green", "qty": 6 } + { "_id": 5, "color": "pink", "qty": 0 } + +The paint store realizes they must update their inventory again. What they +thought was 20 cans of pink paint is actually 25 cans of orange paint. + +To update the inventory, call the ``replaceOne()`` method specifying the +following: + +- A query filter that matches documents where the ``color`` is "pink" +- A replacement document where the ``color`` is "orange" and the ``qty`` is "25" + +.. literalinclude:: /includes/fundamentals/code-snippets/Update.java + :language: java + :dedent: + :start-after: begin replaceOneExample + :end-before: end replaceOneExample + +The output of the preceding code resembles the following: + +.. code-block:: none + :copyable: false + + Matched document count: 1 + Modified document count: 1 + +The following shows the updated document: + +.. code-block:: json + :copyable: false + + { "_id": 5, "color": "orange", "qty": 25 } + +If multiple documents match the query filter specified in +the ``replaceOne()`` method, it replaces the first result. You can +specify a sort in a ``ReplaceOptions`` instance to apply an order to +matched documents before the server performs the replace operation, as +shown in the following code: + +.. literalinclude:: /includes/fundamentals/code-snippets/Update.java + :language: java + :dedent: + :start-after: begin replaceoptions + :end-before: end replaceoptions + +If zero documents match the query filter in the replace operation, +``replaceOne()`` makes no changes to documents in the collection. See +our :ref:`upsert guide ` to +learn how to insert a new document instead of replacing one if no +documents match. + +.. important:: + + The ``replaceOne()`` method cannot make changes to a document that + violate unique index constraints on the collection. + For more information about constraints on unique indexes, + see :manual:`Unique Indexes ` in the + {+mdb-server+} manual. diff --git a/source/crud/transactions.txt b/source/crud/transactions.txt index f9c533412..42a26e888 100644 --- a/source/crud/transactions.txt +++ b/source/crud/transactions.txt @@ -148,7 +148,9 @@ If you require more control over your transactions, you can use the ``startTrans method. You can use this method with the ``commitTransaction()`` and ``abortTransaction()`` methods described in the preceding section to manually manage the transaction lifecycle. -.. sharedinclude:: dbx/transactions-parallelism.rst +.. note:: Parallel Operations Not Supported + + The {+driver-short+} does not support running parallel operations within a single transaction. Additional Information ---------------------- diff --git a/source/crud/write-operations/modify.txt b/source/crud/update-documents.txt similarity index 50% rename from source/crud/write-operations/modify.txt rename to source/crud/update-documents.txt index 88e61f8ba..79441a230 100644 --- a/source/crud/write-operations/modify.txt +++ b/source/crud/update-documents.txt @@ -1,7 +1,10 @@ .. _java-fundamentals-change-document: +.. _java-write-operations: +.. _update-operation: +.. _java-fundamentals-update: ================ -Modify Documents +Update Documents ================ .. contents:: On this page @@ -10,46 +13,37 @@ Modify Documents :depth: 2 :class: singlecol -Overview --------- - -In this guide, you can learn how to modify documents in a MongoDB -collection using two distinct operation types: - -- :ref:`Update ` -- :ref:`Replace ` - -Update operations specify the fields and values to change in one or more -documents. A replace operation specifies the fields and values to replace -a single document from your collection. - -In the following examples, a paint store sells five different -colors of paint. The ``paint_inventory`` collection represents their -current inventory: +.. meta:: + :description: Learn about the commands for running MongoDB write operations by using the {+driver-long+}. -.. code-block:: json +.. toctree:: + :caption: Update Documents + + Update Array Elements + Upsert - { "_id": 1, "color": "red", "qty": 5 } - { "_id": 2, "color": "purple", "qty": 8 } - { "_id": 3, "color": "yellow", "qty": 0 } - { "_id": 4, "color": "green", "qty": 6 } - { "_id": 5, "color": "pink", "qty": 0 } +Overview +-------- -.. _update-operation: +In this guide, you can learn how to update documents in a MongoDB +collection. Update operations specify the fields and values to change in one or more +documents. They apply changes specified in an update document to one or more +documents that match your query filter. -.. _java-fundamentals-update: +To learn how to updated embedded arrays or to update or insert in a +single operation, see the following pages: -Update ------- +- :doc:`/crud/update-documents/embedded-arrays` +- :doc:`/crud/update-documents/upsert` -Update operations can modify fields and values. They apply changes -specified in an update document to one or more documents that match your -query filter. +Update operations can modify fields and values: -The `updateOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#updateOne(org.bson.conversions.Bson,org.bson.conversions.Bson)>`__ -method changes the first document your query filter matches and the -`updateMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#updateMany(org.bson.conversions.Bson,org.bson.conversions.Bson)>`__ -method changes all the documents your query filter matches. +- The `updateOne() + <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#updateOne(org.bson.conversions.Bson,org.bson.conversions.Bson)>`__ + method changes the first document your query filter matches and the +- `updateMany() + <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#updateMany(org.bson.conversions.Bson,org.bson.conversions.Bson)>`__ + method changes all the documents your query filter matches. You can call the ``updateOne()`` and ``updateMany()`` methods on a ``MongoCollection`` instance as follows: @@ -86,6 +80,21 @@ To view a complete list of Updates builders and their usage, see `Updates <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html>`__ in the API documentation. +Examples +-------- + +In the following examples, a paint store sells five different +colors of paint. The ``paint_inventory`` collection represents their +current inventory: + +.. code-block:: json + + { "_id": 1, "color": "red", "qty": 5 } + { "_id": 2, "color": "purple", "qty": 8 } + { "_id": 3, "color": "yellow", "qty": 0 } + { "_id": 4, "color": "green", "qty": 6 } + { "_id": 5, "color": "pink", "qty": 0 } + Update One Example ~~~~~~~~~~~~~~~~~~ @@ -161,98 +170,4 @@ documents match. to a document that violate unique index constraints on the collection. For more information about constraints on unique indexes, see :manual:`Unique Indexes ` in the - {+mdb-server+} manual. - -.. _replace-operation: - -Replace -------- - -A replace operation substitutes one document from your collection. The -substitution occurs between a document your query filter matches and a -replacement document. - -The `replaceOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#replaceOne(org.bson.conversions.Bson,TDocument)>`__ -method removes all the existing fields and values in the -matching document (except the ``_id`` field) and substitutes it with the -replacement document. - -You can call the ``replaceOne()`` method on a ``MongoCollection`` -instance as follows: - -.. code-block:: java - - collection.replaceOne(, ); - -Replace Operation Parameters -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The ``replaceOne()`` method has the following parameters: - -- ``query`` specifies a query filter with the criteria to match a - document to replace in your collection. -- ``replacement`` specifies fields and values of a new ``Document`` - object to replace the matched document. -- *(Optional)* ``replaceOptions`` specifies options that you can set to - customize how the driver performs the replace operation. To learn more - about this type, see the API documentation for `ReplaceOptions - <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/ReplaceOptions.html>`__. - -Replace One Example -~~~~~~~~~~~~~~~~~~~ - -The paint store realizes they must update their inventory again. What they -thought was 20 cans of pink paint is actually 25 cans of orange paint. - -To update the inventory, call the ``replaceOne()`` method specifying the -following: - -- A query filter that matches documents where the ``color`` is "pink" -- A replacement document where the ``color`` is "orange" and the ``qty`` is "25" - -.. literalinclude:: /includes/fundamentals/code-snippets/Update.java - :language: java - :dedent: - :start-after: begin replaceOneExample - :end-before: end replaceOneExample - -The output of the preceding code resembles the following: - -.. code-block:: none - :copyable: false - - Matched document count: 1 - Modified document count: 1 - -The following shows the updated document: - -.. code-block:: json - :copyable: false - - { "_id": 5, "color": "orange", "qty": 25 } - -If multiple documents match the query filter specified in -the ``replaceOne()`` method, it replaces the first result. You can -specify a sort in a ``ReplaceOptions`` instance to apply an order to -matched documents before the server performs the replace operation, as -shown in the following code: - -.. literalinclude:: /includes/fundamentals/code-snippets/Update.java - :language: java - :dedent: - :start-after: begin replaceoptions - :end-before: end replaceoptions - -If zero documents match the query filter in the replace operation, -``replaceOne()`` makes no changes to documents in the collection. See -our :ref:`upsert guide ` to -learn how to insert a new document instead of replacing one if no -documents match. - -.. important:: - - The ``replaceOne()`` method cannot make changes to a document that - violate unique index constraints on the collection. - For more information about constraints on unique indexes, - see :manual:`Unique Indexes ` in the - {+mdb-server+} manual. + {+mdb-server+} manual. \ No newline at end of file diff --git a/source/crud/write-operations/embedded-arrays.txt b/source/crud/update-documents/embedded-arrays.txt similarity index 100% rename from source/crud/write-operations/embedded-arrays.txt rename to source/crud/update-documents/embedded-arrays.txt diff --git a/source/crud/write-operations/upsert.txt b/source/crud/update-documents/upsert.txt similarity index 100% rename from source/crud/write-operations/upsert.txt rename to source/crud/update-documents/upsert.txt diff --git a/source/crud/write-operations.txt b/source/crud/write-operations.txt deleted file mode 100644 index aa0b2d86a..000000000 --- a/source/crud/write-operations.txt +++ /dev/null @@ -1,25 +0,0 @@ -.. _java-write-operations: - -================ -Write Operations -================ - -.. meta:: - :description: Learn about the commands for running MongoDB write operations by using the {+driver-long+}. - -.. toctree:: - :caption: Write Operations - - Insert - Delete - Modify - Update Array Elements - Upsert - Bulk Operations - -- :doc:`/crud/write-operations/insert` -- :doc:`/crud/write-operations/delete` -- :doc:`/crud/write-operations/modify` -- :doc:`/crud/write-operations/embedded-arrays` -- :doc:`/crud/write-operations/upsert` -- :doc:`/crud/write-operations/bulk` diff --git a/source/get-started/databases-collections.txt b/source/databases-collections.txt similarity index 100% rename from source/get-started/databases-collections.txt rename to source/databases-collections.txt diff --git a/source/get-started.txt b/source/get-started.txt index 4dec6ef26..0a2a07058 100644 --- a/source/get-started.txt +++ b/source/get-started.txt @@ -12,16 +12,6 @@ Get Started with the Java Driver :description: Learn how to create an app to connect to MongoDB deployment by using the {+driver-short+}. :keywords: quick start, tutorial, basics -.. toctree:: - - Download & Install - Create a Deployment - Create a Connection String - Connect to MongoDB - Next Steps - Databases & Collections - Integrations - Overview -------- @@ -49,4 +39,212 @@ deployment. The tutorial includes the following sections: that connects to MongoDB and queries data stored in your deployment. If you prefer to connect to MongoDB using a different driver or -programming language, see our :driver:`list of official drivers <>`. \ No newline at end of file +programming language, see our :driver:`list of official drivers <>`. + +.. _java-get-started-download-and-install: + +Download and Install +-------------------- + +Complete the following steps to install the {+driver-short+} and +its dependencies in your development environment. + +.. procedure:: + :style: connected + + .. step:: Install the driver dependencies + + Before you begin this tutorial, ensure that you install + the following dependencies: + + - `JDK `__ + version 8 or later + - Integrated development environment (IDE), such as `IntelliJ IDEA `__ + or `Eclipse `__ + + .. note:: + + This tutorial shows how to install the {+driver-short+} by using + Maven or Gradle in an IDE. If you do not use an IDE, visit `Building Maven + `__ + or `Creating New Gradle Builds `__ + to learn how to set up your project. + + .. step:: Install the {+driver-short+} + + In your IDE, create a new `Maven `__ or `Gradle `__ + project. If you use Maven, add the following code to your ``pom.xml`` dependencies list: + + .. code-block:: xml + + + + org.mongodb + mongodb-driver-sync + {+full-version+} + + + + If you use Gradle, add the following code to your ``build.gradle`` dependencies list: + + .. code-block:: groovy + + dependencies { + implementation 'org.mongodb:mongodb-driver-sync:{+full-version+}' + } + + After you configure your dependencies, ensure they are available to your + project by running your dependency manager and refreshing + the project in your IDE. + +After you complete these steps, you have a new project +and the driver dependencies installed. + +.. _java-get-started-create-deployment: + +Create a MongoDB Deployment +--------------------------- + +You can create a free tier MongoDB deployment on MongoDB Atlas +to store and manage your data. MongoDB Atlas hosts and manages +your MongoDB database in the cloud. + +.. procedure:: + :style: connected + + .. step:: Create a free MongoDB deployment on Atlas + + Complete the :atlas:`Get Started with Atlas ` + guide to set up a new Atlas account and a free tier MongoDB deployment. + Ensure that you :atlas:`load sample data ` and + :atlas:`add your IP address ` to the IP access + list. + + .. step:: Save your credentials + + After you create your database user, save that user's + username and password to a safe location for use in an upcoming step. + +After you complete these steps, you have a new free tier MongoDB +deployment on Atlas, database user credentials, and sample data loaded +in your database. + +.. _java-get-started-connection-string: + +Create a Connection String +-------------------------- + +You can connect to your MongoDB deployment by providing a +**connection URI**, also called a *connection string*, which +instructs the driver on how to connect to a MongoDB deployment +and how to behave while connected. + +The connection string includes the hostname or IP address and +port of your deployment, the authentication mechanism, user credentials +when applicable, and connection options. + +.. procedure:: + :style: connected + + .. step:: Find your MongoDB Atlas connection string + + To retrieve your connection string for the deployment that + you created in the :ref:`previous step `, + log into your Atlas account and navigate to the + :guilabel:`Clusters` section. Click the :guilabel:`Connect` button + for your new deployment, as shown in the following screenshot: + + .. figure:: /includes/figures/atlas_connection_connect_cluster.png + :alt: The connect button in the clusters section of the Atlas UI + + Then, proceed to the :guilabel:`Connect your application` section. Select + "Java" from the :guilabel:`Driver` selection menu and the version + that best matches the version you installed from the :guilabel:`Version` + selection menu. + + .. step:: Copy your connection string + + Click the button on the right of the connection string to copy it to + your clipboard, as shown in the following screenshot: + + .. figure:: /includes/figures/atlas_connection_copy_uri_java.png + :alt: The connection string copy button in the Atlas UI + + .. step:: Edit your connection string placeholders + + Paste your connection string into a file in your preferred text editor + and save this file to a safe location for later use. In your connection + string, replace the ```` and ```` placeholders with + your database user's username and password. + +After completing these steps, you have a connection string that +contains your database username and password. + +Run a Sample Query +------------------ + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :keywords: test connection, runnable, code example + +After retrieving the connection string for your MongoDB Atlas deployment, +you can connect to the deployment from your Java application and query +the Atlas sample datasets. + +.. procedure:: + :style: connected + + .. step:: Create your Java application file + + In your project's base package directory, create a file called + ``QuickStart.java``. Copy and paste the following code into this file, + which queries the ``movies`` collection in the ``sample_mflix`` database: + + .. literalinclude:: /includes/get-started/code-snippets/QuickStart.java + :start-after: begin QuickStart + :end-before: end QuickStart + :language: java + :dedent: + + .. step:: Assign the connection string + + Replace the ```` placeholder with the connection string + that you copied from the :ref:`java-get-started-connection-string` step of this + guide. + + .. step:: Run your Java application + + Run your application in your IDE or your shell. Your output + contains details about the retrieved movie document: + + .. include:: /includes/get-started/query-output.rst + + .. include:: /includes/get-started/jdk-tls-issue.rst + +After you complete these steps, you have a Java application that +connects to your MongoDB deployment, runs a query on the sample +data, and returns a matching document. + +.. _java-get-started-next-steps: + +Next Steps +---------- + +Congratulations on completing the tutorial! + +.. include:: /includes/get-started/quickstart-troubleshoot.rst + +In this tutorial, you created a {+driver-short+} application that +connects to a MongoDB deployment hosted on MongoDB Atlas +and retrieves a document that matches a query. + +You can continue to develop your sample application by +visiting the following guides: + +- :ref:`java-db-coll`: Learn more about interacting with + MongoDB databases and collections. +- :ref:`java-integrations`: Learn about the third-party + integrations that you can use with the {+driver-short+}. \ No newline at end of file diff --git a/source/get-started/connect-to-mongodb.txt b/source/get-started/connect-to-mongodb.txt deleted file mode 100644 index 287892833..000000000 --- a/source/get-started/connect-to-mongodb.txt +++ /dev/null @@ -1,50 +0,0 @@ -================== -Connect to MongoDB -================== - -.. facet:: - :name: genre - :values: tutorial - -.. meta:: - :keywords: test connection, runnable, code example - -After retrieving the connection string for your MongoDB Atlas deployment, -you can connect to the deployment from your Java application and query -the Atlas sample datasets. - -.. procedure:: - :style: connected - - .. step:: Create your Java application file - - In your project's base package directory, create a file called - ``QuickStart.java``. Copy and paste the following code into this file, - which queries the ``movies`` collection in the ``sample_mflix`` database: - - .. literalinclude:: /includes/get-started/code-snippets/QuickStart.java - :start-after: begin QuickStart - :end-before: end QuickStart - :language: java - :dedent: - - .. step:: Assign the connection string - - Replace the ```` placeholder with the connection string - that you copied from the :ref:`java-get-started-connection-string` step of this - guide. - - .. step:: Run your Java application - - Run your application in your IDE or your shell. Your output - contains details about the retrieved movie document: - - .. include:: /includes/get-started/query-output.rst - - .. include:: /includes/get-started/jdk-tls-issue.rst - -After you complete these steps, you have a Java application that -connects to your MongoDB deployment, runs a query on the sample -data, and returns a matching document. - -.. include:: /includes/get-started/quickstart-troubleshoot.rst diff --git a/source/get-started/connection-string.txt b/source/get-started/connection-string.txt deleted file mode 100644 index d5e1dc250..000000000 --- a/source/get-started/connection-string.txt +++ /dev/null @@ -1,53 +0,0 @@ -.. _java-get-started-connection-string: - -========================== -Create a Connection String -========================== - -You can connect to your MongoDB deployment by providing a -**connection URI**, also called a *connection string*, which -instructs the driver on how to connect to a MongoDB deployment -and how to behave while connected. - -The connection string includes the hostname or IP address and -port of your deployment, the authentication mechanism, user credentials -when applicable, and connection options. - -.. procedure:: - :style: connected - - .. step:: Find your MongoDB Atlas connection string - - To retrieve your connection string for the deployment that - you created in the :ref:`previous step `, - log into your Atlas account and navigate to the - :guilabel:`Clusters` section. Click the :guilabel:`Connect` button - for your new deployment, as shown in the following screenshot: - - .. figure:: /includes/figures/atlas_connection_connect_cluster.png - :alt: The connect button in the clusters section of the Atlas UI - - Then, proceed to the :guilabel:`Connect your application` section. Select - "Java" from the :guilabel:`Driver` selection menu and the version - that best matches the version you installed from the :guilabel:`Version` - selection menu. - - .. step:: Copy your connection string - - Click the button on the right of the connection string to copy it to - your clipboard, as shown in the following screenshot: - - .. figure:: /includes/figures/atlas_connection_copy_uri_java.png - :alt: The connection string copy button in the Atlas UI - - .. step:: Edit your connection string placeholders - - Paste your connection string into a file in your preferred text editor - and save this file to a safe location for later use. In your connection - string, replace the ```` and ```` placeholders with - your database user's username and password. - -After completing these steps, you have a connection string that -contains your database username and password. - -.. include:: /includes/get-started/quickstart-troubleshoot.rst \ No newline at end of file diff --git a/source/get-started/create-deployment.txt b/source/get-started/create-deployment.txt deleted file mode 100644 index adf078dbe..000000000 --- a/source/get-started/create-deployment.txt +++ /dev/null @@ -1,29 +0,0 @@ -.. _java-get-started-create-deployment: - -=========================== -Create a MongoDB Deployment -=========================== - -You can create a free tier MongoDB deployment on MongoDB Atlas -to store and manage your data. MongoDB Atlas hosts and manages -your MongoDB database in the cloud. - -.. procedure:: - :style: connected - - .. step:: Create a free MongoDB deployment on Atlas - - Complete the :atlas:`Get Started with Atlas ` - guide to set up a new Atlas account and a free tier MongoDB deployment. - Ensure that you :atlas:`load sample data ` and - :atlas:`add your IP address ` to the IP access - list. - - .. step:: Save your credentials - - After you create your database user, save that user's - username and password to a safe location for use in an upcoming step. - -After you complete these steps, you have a new free tier MongoDB -deployment on Atlas, database user credentials, and sample data loaded -in your database. \ No newline at end of file diff --git a/source/get-started/download-and-install.txt b/source/get-started/download-and-install.txt deleted file mode 100644 index 25809997f..000000000 --- a/source/get-started/download-and-install.txt +++ /dev/null @@ -1,61 +0,0 @@ -.. _java-get-started-download-and-install: - -==================== -Download and Install -==================== - -Complete the following steps to install the {+driver-short+} and -its dependencies in your development environment. - -.. procedure:: - :style: connected - - .. step:: Install the driver dependencies - - Before you begin this tutorial, ensure that you install - the following dependencies: - - - `JDK `__ - version 8 or later - - Integrated development environment (IDE), such as `IntelliJ IDEA `__ - or `Eclipse `__ - - .. note:: - - This tutorial shows how to install the {+driver-short+} by using - Maven or Gradle in an IDE. If you do not use an IDE, visit `Building Maven - `__ - or `Creating New Gradle Builds `__ - to learn how to set up your project. - - .. step:: Install the {+driver-short+} - - In your IDE, create a new `Maven `__ or `Gradle `__ - project. If you use Maven, add the following code to your ``pom.xml`` dependencies list: - - .. code-block:: xml - - - - org.mongodb - mongodb-driver-sync - {+full-version+} - - - - If you use Gradle, add the following code to your ``build.gradle`` dependencies list: - - .. code-block:: groovy - - dependencies { - implementation 'org.mongodb:mongodb-driver-sync:{+full-version+}' - } - - After you configure your dependencies, ensure they are available to your - project by running your dependency manager and refreshing - the project in your IDE. - -After you complete these steps, you have a new project -and the driver dependencies installed. - -.. include:: /includes/get-started/quickstart-troubleshoot.rst \ No newline at end of file diff --git a/source/get-started/next-steps.txt b/source/get-started/next-steps.txt deleted file mode 100644 index 8be4e1fb3..000000000 --- a/source/get-started/next-steps.txt +++ /dev/null @@ -1,19 +0,0 @@ -.. _java-get-started-next-steps: - -========== -Next Steps -========== - -Congratulations on completing the tutorial! - -In this tutorial, you created a {+driver-short+} application that -connects to a MongoDB deployment hosted on MongoDB Atlas -and retrieves a document that matches a query. - -You can continue to develop your sample application by -visiting the following guides: - -- :ref:`java-db-coll`: Learn more about interacting with - MongoDB databases and collections. -- :ref:`java-integrations`: Learn about the third-party - integrations that you can use with the {+driver-short+}. \ No newline at end of file diff --git a/source/includes/crud/example-intro.rst b/source/includes/crud/example-intro.rst new file mode 100644 index 000000000..e2b1374dd --- /dev/null +++ b/source/includes/crud/example-intro.rst @@ -0,0 +1,10 @@ +.. note:: Example Setup + + This example connects to an instance of MongoDB by using a connection URI. To learn + more about connecting to your MongoDB instance, see the :ref:`connection guide + `. This example also uses the ``movies`` collection in the + ``sample_mflix`` database included in the :atlas:`Atlas sample datasets + `. You can load them into + your database on the free tier of MongoDB Atlas by following the :atlas:`Get + Started with Atlas Guide + `. \ No newline at end of file diff --git a/source/includes/crud/read-write-pref-concerns.rst b/source/includes/crud/read-write-pref-concerns.rst new file mode 100644 index 000000000..afae0d46e --- /dev/null +++ b/source/includes/crud/read-write-pref-concerns.rst @@ -0,0 +1,10 @@ +**Read preferences**, **read concerns**, and **write concerns** control +how the driver routes read operations and waits for acknowledgment for +read and write operations when connected to a MongoDB replica set. +Read preferences and read concerns apply to all read operations; +write concerns apply to all write operations. + +For more information, see the server documentation on +:manual:`read preferences `, +:manual:`read concerns `, and +:manual:`write concerns `. \ No newline at end of file diff --git a/source/includes/fundamentals/code-snippets/MCSettings.java b/source/includes/fundamentals/code-snippets/MCSettings.java index c38717be8..863e5da1b 100644 --- a/source/includes/fundamentals/code-snippets/MCSettings.java +++ b/source/includes/fundamentals/code-snippets/MCSettings.java @@ -89,7 +89,8 @@ private static void createSocketSettings() { try { //begin SocketSettings MongoClient mongoClient = MongoClients.create( - MongoClientSettings.builder().applyConnectionString(new ConnectionString("")) + MongoClientSettings.builder() + .applyConnectionString(new ConnectionString("")) .applyToSocketSettings(builder -> builder.connectTimeout(10, SECONDS) .readTimeout(15, SECONDS)) @@ -140,6 +141,7 @@ private static void createLoggerSettings() { ////begin LoggerSettings MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder().applyConnectionString(new ConnectionString("")) + .applicationName("") .applyToLoggerSettings(builder -> builder.maxDocumentLength(5_000)) .build()); @@ -150,4 +152,19 @@ private static void createLoggerSettings() { System.out.print("---------------------------------------"); } } + + private static void createReadConcern() { + try { + ////begin ReadConcern + MongoClient mongoClient = MongoClients.create( + MongoClientSettings.builder().applyConnectionString(new ConnectionString("")) + .readPreference(ReadPreference.nearest()) + .build()); + //end ReadConcern + mongoClient.listDatabaseNames().forEach(n -> System.out.println(n)); + mongoClient.close(); + } finally { + System.out.print("---------------------------------------"); + } + } } \ No newline at end of file diff --git a/source/includes/get-started/quickstart-troubleshoot.rst b/source/includes/get-started/quickstart-troubleshoot.rst index 390289f41..803f050a2 100644 --- a/source/includes/get-started/quickstart-troubleshoot.rst +++ b/source/includes/get-started/quickstart-troubleshoot.rst @@ -1,6 +1,6 @@ .. note:: - If you run into issues on this step, ask for help in the + If you run into issues in this tutorial, ask for help in the :community-forum:`MongoDB Community Forums ` or submit feedback by using the :guilabel:`Rate this page` tab on the right or bottom right side of this page. \ No newline at end of file diff --git a/source/includes/logging-monitoring/logging-monitoring-pages.rst b/source/includes/logging-monitoring/logging-monitoring-pages.rst new file mode 100644 index 000000000..188343270 --- /dev/null +++ b/source/includes/logging-monitoring/logging-monitoring-pages.rst @@ -0,0 +1,3 @@ +- :ref:`Logging ` +- :ref:`Monitoring ` +- :ref:`Change Streams ` \ No newline at end of file diff --git a/source/index.txt b/source/index.txt index 06b623cd3..b266d7c95 100644 --- a/source/index.txt +++ b/source/index.txt @@ -20,15 +20,19 @@ MongoDB Java Driver Get Started Connect + Databases & Collections CRUD Operations + Aggregation + Builders Data Formats Indexes Run a Command - Atlas Search + Atlas Search Atlas Vector Search Logging and Monitoring Security - Versioning + Third-Party Integrations + Reference API Documentation Issues & Help diff --git a/source/get-started/integrations.txt b/source/integrations.txt similarity index 98% rename from source/get-started/integrations.txt rename to source/integrations.txt index d8929a1ca..fa329cc8a 100644 --- a/source/get-started/integrations.txt +++ b/source/integrations.txt @@ -1,8 +1,8 @@ .. _java-integrations: -=================== -Driver Integrations -=================== +======================== +Third-Party Integrations +======================== .. facet:: :name: genre diff --git a/source/logging-monitoring.txt b/source/logging-monitoring.txt index af9de0f1b..5241c7144 100644 --- a/source/logging-monitoring.txt +++ b/source/logging-monitoring.txt @@ -1,3 +1,5 @@ +.. _java-logging-monitoring: + ====================== Logging and Monitoring ====================== @@ -11,4 +13,12 @@ Logging and Monitoring Logging Monitoring - Change Streams \ No newline at end of file + Change Streams + +Overview +-------- + +Learn how to set up logging and monitoring for your application in +the following sections: + +.. include:: /includes/logging-monitoring/logging-monitoring-pages.rst \ No newline at end of file diff --git a/source/logging-monitoring/logging.txt b/source/logging-monitoring/logging.txt index 3bd5bc7af..ed82a95b8 100644 --- a/source/logging-monitoring/logging.txt +++ b/source/logging-monitoring/logging.txt @@ -461,3 +461,59 @@ project. For more information about configuring Log4j2, see the `official Log4J2 configuration guide `__. + +.. _mcs-logger-settings: + +Connection Settings +------------------- + +You can apply logging settings to your ``MongoClient`` instance using the `applyToLoggerSettings() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html#applyToLoggerSettings(com.mongodb.Block)>`__ +and `applicationName() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html#applicationName(java.lang.String)>`__ methods. + +The following table describes the methods you can chain to your +logger settings to modify the logging behavior: + +.. list-table:: + :widths: 40 60 + :header-rows: 1 + + * - Method + - Description + + * - ``maxDocumentLength()`` + - Sets the maximum document length, in characters, of a single log message. + + **Default**: ``1000`` + +Example +~~~~~~~ + +This example names the application sending requests and specifies that the maximum number of characters for a single log message is set to ``5000`` characters. + +.. literalinclude:: /includes/fundamentals/code-snippets/MCSettings.java + :start-after: begin LoggerSettings + :end-before: end LoggerSettings + :language: java + :emphasize-lines: 3-4 + :dedent: + +You should see output that resembles the following: + +.. code-block:: none + :copyable: false + + 01:20:38.782 [main] INFO org.mongodb.driver.client -- MongoClient with + metadata {"application": {"name": ""}, ..., + loggerSettings=LoggerSettings{maxDocumentLength=5000}, ... timeoutMS=null} + ... + 01:20:41.022 [main] DEBUG org.mongodb.driver.protocol.command -- Command + "listDatabases" succeeded ... Command reply: {"databases": [...], ...} + 01:20:41.024 [main] DEBUG org.mongodb.driver.connection -- Connection checked in: address=
, driver-generated ID=6 + myDb + sample_airbnb + sample_analytics + ... + +For more information, see the `MongoClientSettings.Builder +<{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html>`__ +API documentation. \ No newline at end of file diff --git a/source/logging-monitoring/monitoring.txt b/source/logging-monitoring/monitoring.txt index bd4137f88..be1d6116a 100644 --- a/source/logging-monitoring/monitoring.txt +++ b/source/logging-monitoring/monitoring.txt @@ -230,10 +230,7 @@ A connection pool event is an event related to a **connection pool** held by the A connection pool is a set of open TCP connections your driver maintains with a MongoDB instance. Connection pools help reduce the number of network handshakes your application needs to perform with a MongoDB instance and can help your -application run faster. - -.. Add when page is ready: To learn more about connection pools, see the {+driver-short+}'s -.. :ref:`Connection Pools ` guide. +application run faster. To learn more about connection pools, see the {+driver-short+}'s :ref:`Connection Pools ` guide. To monitor connection pool events, write a class that implements the ``ConnectionPoolListener`` interface and register an instance of that class with your diff --git a/source/reference.txt b/source/reference.txt new file mode 100644 index 000000000..303f41879 --- /dev/null +++ b/source/reference.txt @@ -0,0 +1,16 @@ +========= +Reference +========= + +.. meta:: + :description: Find references material for the {+driver-long+}. + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Release Notes + Compatibility + Third-Party Integrations + Upgrade + Migrate from the Legacy API \ No newline at end of file diff --git a/source/versioning/compatibility.txt b/source/references/compatibility.txt similarity index 100% rename from source/versioning/compatibility.txt rename to source/references/compatibility.txt diff --git a/source/versioning/legacy.txt b/source/references/legacy.txt similarity index 100% rename from source/versioning/legacy.txt rename to source/references/legacy.txt diff --git a/source/versioning/upgrade.txt b/source/references/upgrade.txt similarity index 100% rename from source/versioning/upgrade.txt rename to source/references/upgrade.txt diff --git a/source/versioning/whats-new.txt b/source/references/whats-new.txt similarity index 100% rename from source/versioning/whats-new.txt rename to source/references/whats-new.txt diff --git a/source/security.txt b/source/security.txt index 15a5d2a07..84ff04a9d 100644 --- a/source/security.txt +++ b/source/security.txt @@ -1,8 +1,8 @@ .. _java-security: -======== -Security -======== +=========================== +Security and Authentication +=========================== .. meta:: :description: Learn how to use security features with the {+driver-long+}. @@ -20,7 +20,7 @@ Security Overview -------- -Learn how to set up security options for your application in the following -sections: +Learn how to set up security and authentication options for your application in +the following sections: .. include:: /includes/security/security-pages.rst \ No newline at end of file diff --git a/source/security/encrypt-fields.txt b/source/security/encrypt-fields.txt index 2419c2178..8cd36addc 100644 --- a/source/security/encrypt-fields.txt +++ b/source/security/encrypt-fields.txt @@ -26,3 +26,22 @@ :tabid: gradle-dependency .. include:: /includes/fundamentals/code-snippets/crypt-gradle-versioned.rst + +Connection Settings +------------------- + +You can apply encryption settings when creating a ``MongoClient`` instance by +passing an `AutoEncryptionSettings +<{+api+}/apidocs/mongodb-driver-core/com/mongodb/AutoEncryptionSettings.html>`__ +object to the `autoEncryptionSettings() +<{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html#autoEncryptionSettings(com.mongodb.AutoEncryptionSettings)>`__ +method. + +.. TODO: Add example + +.. note:: + + If you omit ``keyVaultClient`` or set ``bypassAutomaticEncryption`` to false + in your ``AutoEncryptionSettings``, the driver creates a separate, internal + ``MongoClient``. The internal ``MongoClient`` configuration differs from the + parent ``MongoClient`` by setting the ``minPoolSize`` to 0 and omitting the ``AutoEncryptionSettings``. \ No newline at end of file diff --git a/source/security/socks.txt b/source/security/socks.txt index 05f513b1f..bbbdfc8a7 100644 --- a/source/security/socks.txt +++ b/source/security/socks.txt @@ -55,11 +55,14 @@ The following table describes the SOCKS5 client options: - String - Specifies the SOCKS5 proxy IPv4 address, IPv6 address, or hostname. You must provide this value to connect to a SOCKS5 proxy. + | + | **Default**: ``null`` * - **proxyPort** - non-negative Integer - - Specifies the TCP port number of the SOCKS5 proxy server. This option - defaults to ``1080`` when you set ``proxyHost``. + - | Specifies the TCP port number of the SOCKS5 proxy server. + | + | **Default**: ``1080`` when you set ``proxyHost`` * - **proxyUsername** - String @@ -67,6 +70,8 @@ The following table describes the SOCKS5 client options: The driver ignores ``null`` and empty string values for this setting. The driver requires that you pass values for both ``proxyUsername`` and ``proxyPassword`` or that you omit both values. + | + | **Default**: ``null`` * - **proxyPassword** - String @@ -75,6 +80,8 @@ The following table describes the SOCKS5 client options: The driver requires that you pass values for both ``proxyUsername`` and ``proxyPassword`` or that you omit both values. + | **Default**: ``null`` + Examples -------- diff --git a/source/security/tls.txt b/source/security/tls.txt index a84d4ddec..27cb2d988 100644 --- a/source/security/tls.txt +++ b/source/security/tls.txt @@ -36,6 +36,7 @@ or `MongoClientSettings <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoCl for more information. .. _tls-enable: +.. _mcs-ssl-settings: Enable TLS/SSL -------------- @@ -68,23 +69,90 @@ using a method in the ``MongoClientSettings.Builder`` class. .. code-block:: java MongoClient mongoClient = MongoClients.create("mongodb+srv://:@?tls=true"); + + The following table describes the parameter you can include in your + connection string to modify the driver's TSL behavior: + + .. list-table:: + :header-rows: 1 + :widths: 20 10 20 + + * - Option Name + - Type + - Description + + * - **ssl** + - boolean + - Specifies that all communication with MongoDB instances must + use TLS/SSL. Superseded by the **tls** option. + + | **Default**: ``false`` + + * - **tls** + - boolean + - Specifies that all communication with MongoDB instances must + use TLS. Supersedes the **ssl** option. + + | **Default**: ``false`` + + * - **tlsInsecure** + - boolean + - Specifies that the driver must allow invalid hostnames for TLS + connections. Has the same effect as setting + **tlsAllowInvalidHostnames** to ``true``. To configure TLS security + constraints in other ways, use a + :ref:`custom SSLContext `. + + | **Default**: ``false`` + + * - **tlsAllowInvalidHostnames** + - boolean + - Specifies that the driver must allow invalid hostnames in the + certificate for TLS connections. Supersedes + **sslInvalidHostNameAllowed**. + + | **Default**: ``false`` .. tab:: MongoClientSettings :tabid: mongoclientsettings To configure your ``MongoClient``'s TLS/SSL connection options using the - ``MongoClientSettings.Builder`` class, call the + ``MongoClientSettings.Builder`` class, chain the `applyToSslSettings() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html#applyToSslSettings(com.mongodb.Block)>`__ method. Set the ``enabled`` property to ``true`` in the ``SslSettings.Builder`` block to enable TLS/SSL: - .. code-block:: java + .. literalinclude:: /includes/fundamentals/code-snippets/MCSettings.java + :start-after: begin SslSettings + :end-before: end SslSettings + :language: java + :emphasize-lines: 3-4 + :dedent: + + The following table describes the methods you can chain to your + settings to modify the driver's TSL behavior: + + .. list-table:: + :widths: 40 60 + :header-rows: 1 + + * - Method + - Description + + * - ``applyConnectionString()`` + - Uses the settings from a ``ConnectionString`` object. + + * - ``applySettings()`` + - Uses the TLS/SSL settings specified in a ``SslSettings`` object. + + * - ``context()`` + - Sets the ``SSLContext`` for use when you enable TLS/SSL. + + * - ``enabled()`` + - Whether to enable TLS/SSL. (You must enable this for Atlas clusters.) - MongoClientSettings settings = MongoClientSettings.builder() - .applyToSslSettings(builder -> - builder.enabled(true)) - .build(); - MongoClient client = MongoClients.create(settings); + * - ``invalidHostNameAllowed()`` + - Whether to allow a mismatch between the server's hostname and the hostname specified by the TLS certificate. .. _tls_configure-certificates: diff --git a/source/usage-examples/find.txt b/source/usage-examples/find.txt index d619e149b..d5ee25489 100644 --- a/source/usage-examples/find.txt +++ b/source/usage-examples/find.txt @@ -13,7 +13,7 @@ the collection. If you do not include a filter, MongoDB returns all the documents in the collection. For more information about querying MongoDB with the Java driver, see our -:doc:`guide on Querying Documents `. +:doc:`guide on Querying Documents `. You can also chain methods to the ``find()`` method such as ``sort()`` which organizes the matched documents in a specified order and @@ -21,9 +21,9 @@ organizes the matched documents in a specified order and returned documents. For more information about the ``sort()`` method, see our -:doc:`guide on Sorting `. +:doc:`guide on Sorting `. For more information about the ``projection()`` method, see our -:doc:`guide on Projections ` +:doc:`guide on Projections ` The ``find()`` method returns an instance of ``FindIterable``, a class that offers several methods to access, organize, and traverse the results. diff --git a/source/usage-examples/findOne.txt b/source/usage-examples/findOne.txt index ba7aac213..f6bfd7366 100644 --- a/source/usage-examples/findOne.txt +++ b/source/usage-examples/findOne.txt @@ -14,16 +14,16 @@ include a filter, MongoDB returns all the documents in the collection. The ``first()`` method returns the first matching document. For more information about querying MongoDB with the Java driver, see our -:doc:`guide on Querying Documents `. +:doc:`guide on Querying Documents `. You can also chain other methods to the ``find()`` method such as ``sort()`` which organizes the matched documents in a specified order, and ``projection()`` which configures the fields included in the returned documents. For more information about the ``sort()`` method, see our -:doc:`guide on Sorting `. +:doc:`guide on Sorting `. For more information about the ``projection()`` method, see our -:doc:`guide on Projections ` +:doc:`guide on Projections ` The ``find()`` method returns an instance of ``FindIterable``, a class that offers several methods to access, organize, and traverse the results. diff --git a/source/versioning.txt b/source/versioning.txt deleted file mode 100644 index 90c9e35b6..000000000 --- a/source/versioning.txt +++ /dev/null @@ -1,15 +0,0 @@ -========== -Versioning -========== - -.. meta:: - :description: Learn about versioning in the {+driver-long+}. - -.. toctree:: - :titlesonly: - :maxdepth: 1 - - Release Notes - Compatibility - Upgrade - Migrate from the Legacy API \ No newline at end of file