diff --git a/.github/workflows/backport.yml b/.github/workflows/backport.yml new file mode 100644 index 000000000..971e8a650 --- /dev/null +++ b/.github/workflows/backport.yml @@ -0,0 +1,26 @@ +name: Backport +on: + pull_request_target: + types: + - closed + - labeled + +jobs: + backport: + name: Backport + runs-on: ubuntu-latest + # Only react to merged PRs for security reasons. + # See https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target. + if: > + github.event.pull_request.merged + && ( + github.event.action == 'closed' + || ( + github.event.action == 'labeled' + && contains(github.event.label.name, 'backport') + ) + ) + steps: + - uses: tibdex/backport@v2 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/check-autobuilder.yml b/.github/workflows/check-autobuilder.yml deleted file mode 100644 index 8495db969..000000000 --- a/.github/workflows/check-autobuilder.yml +++ /dev/null @@ -1,13 +0,0 @@ -name: Check Autobuilder for Errors - -on: - pull_request: - paths: - - "source/**" - -jobs: - check: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - uses: cbush/snooty-autobuilder-check@main diff --git a/build.sh b/build.sh new file mode 100644 index 000000000..b62b6772f --- /dev/null +++ b/build.sh @@ -0,0 +1,8 @@ +# ensures that we always use the latest version of the script +if [ -f build-site.sh ]; then + rm build-site.sh +fi + + +curl https://raw.githubusercontent.com/mongodb/docs-worker-pool/netlify-poc/scripts/build-site.sh -o build-site.sh +sh build-site.sh \ No newline at end of file diff --git a/config/redirects b/config/redirects index 5175739e5..88042cc3a 100644 --- a/config/redirects +++ b/config/redirects @@ -5,9 +5,68 @@ define: versions v4.3 v4.4 v4.5 v4.6 v4.7 v4.8 v4.9 v4.10 v4.11 v5.0 v5.1 master raw: ${prefix}/ -> ${base}/current/ raw: ${prefix}/master -> ${base}/upcoming/ -[*-master]: ${prefix}/${version}/fundamentals/versioned-api/ -> ${base}/${version}/fundamentals/stable-api/ +[*-v5.2]: ${prefix}/${version}/fundamentals/versioned-api/ -> ${base}/${version}/fundamentals/stable-api/ [*-v4.6]: ${prefix}/${version}/fundamentals/crud/read-operations/change-streams/ -> ${base}/${version}/fundamentals/crud/read-operations/retrieve/ [*-master]: ${prefix}/${version}/fundamentals/csfle/ -> ${base}/${version}/fundamentals/encrypt-fields/ [*-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}/ +[v5.0-master]: ${prefix}/${version}/fundamentals/crud/ -> ${base}/${version}/crud/ +[v5.0-master]: ${prefix}/${version}/fundamentals/crud/read-operations/ -> ${base}/${version}/crud/read-operations/ +[v5.0-master]: ${prefix}/${version}/fundamentals/crud/read-operations/retrieve/ -> ${base}/${version}/crud/read-operations/retrieve/ +[v5.0-master]: ${prefix}/${version}/fundamentals/crud/read-operations/cursor/ -> ${base}/${version}/crud/read-operations/cursor/ +[v5.0-master]: ${prefix}/${version}/fundamentals/crud/read-operations/change-streams/ -> ${base}/${version}/logging-monitoring/change-streams/ +[v5.0-master]: ${prefix}/${version}/fundamentals/crud/read-operations/sort/ -> ${base}/${version}/crud/read-operations/sort/ +[v5.0-master]: ${prefix}/${version}/fundamentals/crud/read-operations/skip/ -> ${base}/${version}/crud/read-operations/skip/ +[v5.0-master]: ${prefix}/${version}/fundamentals/crud/read-operations/limit/ -> ${base}/${version}/crud/read-operations/limit/ +[v5.0-master]: ${prefix}/${version}/fundamentals/crud/read-operations/project/ -> ${base}/${version}/crud/read-operations/project/ +[v5.0-master]: ${prefix}/${version}/fundamentals/crud/read-operations/geo/ -> ${base}/${version}/crud/read-operations/geo/ +[v5.0-master]: ${prefix}/${version}/fundamentals/crud/read-operations/text/ -> ${base}/${version}/crud/read-operations/text/ +[v5.0-master]: ${prefix}/${version}/fundamentals/crud/write-operations/ -> ${base}/${version}/crud/write-operations/ +[v5.0-master]: ${prefix}/${version}/fundamentals/crud/write-operations/insert/ -> ${base}/${version}/crud/write-operations/insert/ +[v5.0-master]: ${prefix}/${version}/fundamentals/crud/write-operations/delete/ -> ${base}/${version}/crud/write-operations/delete/ +[v5.0-master]: ${prefix}/${version}/fundamentals/crud/write-operations/modify/ -> ${base}/${version}/crud/write-operations/modify/ +[v5.0-master]: ${prefix}/${version}/fundamentals/crud/write-operations/embedded-arrays/ -> ${base}/${version}/crud/write-operations/embedded-arrays/ +[v5.0-master]: ${prefix}/${version}/fundamentals/crud/write-operations/upsert/ -> ${base}/${version}/crud/write-operations/upsert/ +[v5.0-master]: ${prefix}/${version}/fundamentals/crud/write-operations/bulk/ -> ${base}/${version}/crud/write-operations/bulk/ +[v5.0-master]: ${prefix}/${version}/fundamentals/crud/query-document/ -> ${base}/${version}/crud/query-document/ +[v5.0-master]: ${prefix}/${version}/fundamentals/crud/compound-operations/ -> ${base}/${version}/crud/compound-operations/ +[v5.0-master]: ${prefix}/${version}/fundamentals/data-formats/ -> ${base}/${version}/data-formats/ +[v5.0-master]: ${prefix}/${version}/fundamentals/data-formats/document-data-format-bson/ -> ${base}/${version}/data-formats/document-data-format-bson/ +[v5.0-master]: ${prefix}/${version}/fundamentals/data-formats/document-data-format-extended-json/ -> ${base}/${version}/data-formats/document-data-format-extended-json/ +[v5.0-master]: ${prefix}/${version}/fundamentals/data-formats/documents/ -> ${base}/${version}/data-formats/documents/ +[v5.0-master]: ${prefix}/${version}/fundamentals/data-formats/document-data-format-pojo/ -> ${base}/${version}/data-formats/document-data-format-pojo/ +[v5.0-master]: ${prefix}/${version}/fundamentals/data-formats/document-data-format-record/ -> ${base}/${version}/data-formats/document-data-format-record/ +[v5.0-master]: ${prefix}/${version}/fundamentals/data-formats/pojo-customization/ -> ${base}/${version}/data-formats/pojo-customization/ +[v5.0-master]: ${prefix}/${version}/fundamentals/data-formats/codecs/ -> ${base}/${version}/data-formats/codecs/ +[v5.0-master]: ${prefix}/${version}/fundamentals/connection/ -> ${base}/${version}/connection/ +[v5.0-master]: ${prefix}/${version}/fundamentals/connection/connect/ -> ${base}/${version}/connection/connect/ +[v5.0-master]: ${prefix}/${version}/fundamentals/connection/connection-options/ -> ${base}/${version}/connection/connection-options/ +[v5.0-master]: ${prefix}/${version}/fundamentals/connection/mongoclientsettings/ -> ${base}/${version}/connection/mongoclientsettings/ +[v5.0-master]: ${prefix}/${version}/fundamentals/connection/network-compression/ -> ${base}/${version}/connection/network-compression/ +[v5.0-master]: ${prefix}/${version}/fundamentals/connection/socks/ -> ${base}/${version}/connection/socks/ +[v5.0-master]: ${prefix}/${version}/fundamentals/connection/tls/ -> ${base}/${version}/security/tls/ +[v5.0-master]: ${prefix}/${version}/fundamentals/connection/jndi/ -> ${base}/${version}/connection/jndi/ +[v5.0-master]: ${prefix}/${version}/fundamentals/builders/ -> ${base}/${version}/crud/builders/ +[v5.0-master]: ${prefix}/${version}/fundamentals/builders/aggregates/ -> ${base}/${version}/crud/builders/aggregates/ +[v5.0-master]: ${prefix}/${version}/fundamentals/builders/filters/ -> ${base}/${version}/crud/builders/filters/ +[v5.0-master]: ${prefix}/${version}/fundamentals/builders/indexes/ -> ${base}/${version}/crud/builders/indexes/ +[v5.0-master]: ${prefix}/${version}/fundamentals/builders/projections/ -> ${base}/${version}/crud/builders/projections/ +[v5.0-master]: ${prefix}/${version}/fundamentals/builders/sort/ -> ${base}/${version}/crud/builders/sort/ +[v5.0-master]: ${prefix}/${version}/fundamentals/builders/updates/ -> ${base}/${version}/crud/builders/updates/ +[v5.0-master]: ${prefix}/${version}/fundamentals/builders/vector-search -> ${base}/${version}/atlas-vector-search/ +[v5.0-master]: ${prefix}/${version}/fundamentals/aggregation/ -> ${base}/${version}/crud/aggregation/ +[v5.0-master]: ${prefix}/${version}/fundamentals/aggregation-expression-operations/ -> ${base}/${version}/crud/aggregation-expression-operations/ +[v5.0-master]: ${prefix}/${version}/fundamentals/collations/ -> ${base}/${version}/crud/collations/ +[v5.0-master]: ${prefix}/${version}/fundamentals/stable-api/ -> ${base}/${version}/connection/stable-api/ +[v5.0-master]: ${prefix}/${version}/connection-troubleshooting/ -> ${base}/${version}/connection/connection-troubleshooting/ +[v5.0-master]: ${prefix}/${version}/fundamentals/gridfs/ -> ${base}/${version}/crud/gridfs/ +[v5.0-master]: ${prefix}/${version}/fundamentals/transactions/ -> ${base}/${version}/crud/transactions/ +[v5.0-master]: ${prefix}/${version}/fundamentals/time-series/ -> ${base}/${version}/data-formats/time-series/ +[v5.0-master]: ${prefix}/${version}/quick-start/ -> ${base}/${version}/getting-started/ +[v5.0-master]: ${prefix}/${version}/fundamentals/databases-collections/ -> ${base}/${version}/getting-started/databases-collections/ +[v5.0-master]: ${prefix}/${version}/integrations/ -> ${base}/${version}/getting-started/integrations/ +[v5.0-master]: ${prefix}/${version}/quick-reference/ -> ${base}/${version}/getting-started/quick-reference/ +[v5.0-master]: ${prefix}/${version}/fundamentals/enterprise-auth/ -> ${base}/${version}/security/enterprise-auth/ +[v5.0-master]: ${prefix}/${version}/connection/socks/ -> ${base}/${version}/security/socks/ +[v5.0-*]: ${prefix}/${version}/whats-new/ -> ${base}/${version}/reference/release-notes/ diff --git a/netlify.toml b/netlify.toml new file mode 100644 index 000000000..2d0a3b987 --- /dev/null +++ b/netlify.toml @@ -0,0 +1,9 @@ +[[integrations]] +name = "snooty-cache-plugin" + +# Production context: all deploys from the Production branch +# set in your site’s Branches settings in the UI will inherit +# these settings. +[build] +publish = "snooty/public" +command = ". ./build.sh" diff --git a/snooty.toml b/snooty.toml index dc73f4597..b4b5dfff1 100644 --- a/snooty.toml +++ b/snooty.toml @@ -7,11 +7,13 @@ intersphinx = [ ] toc_landing_pages = [ - "/fundamentals/connection", - "/fundamentals/crud", - "/fundamentals/builders", - "/fundamentals/aggregation", - "/usage-examples", + "/get-started", + "/connection", + "/crud", + "/aggregation", + "/builders", + "/data-formats", + "/api-documentation", ] sharedinclude_root = "https://raw.githubusercontent.com/10gen/docs-shared/main/" @@ -20,12 +22,12 @@ driver = "java" driver-long = "MongoDB Java Driver" driver-short = "Java driver" version = "5.1" -full-version = "{+version+}.0" +full-version = "{+version+}.4" mdb-server = "MongoDB Server" package-name-org = "mongodb-org" api = "https://mongodb.github.io/mongo-java-driver/{+version+}" stable-api = "Stable API" -mongocrypt-version = "1.7.3" +mongocrypt-version = "1.8.0" nettyVersion = "io.netty:netty-all:4.1.87.Final" snappyVersion = "org.xerial.snappy:snappy-java:1.1.10.3" zstdVersion = "com.github.luben:zstd-jni:1.5.5-3" diff --git a/source/fundamentals/aggregation.txt b/source/aggregation.txt similarity index 98% rename from source/fundamentals/aggregation.txt rename to source/aggregation.txt index 0b6f5d247..a6a032035 100644 --- a/source/fundamentals/aggregation.txt +++ b/source/aggregation.txt @@ -17,6 +17,12 @@ Aggregation :depth: 2 :class: singlecol +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Aggregation Expressions + Overview -------- diff --git a/source/fundamentals/aggregation-expression-operations.txt b/source/aggregation/aggregation-expression-operations.txt similarity index 100% rename from source/fundamentals/aggregation-expression-operations.txt rename to source/aggregation/aggregation-expression-operations.txt diff --git a/source/atlas-search.txt b/source/atlas-search.txt new file mode 100644 index 000000000..6cfbc27d1 --- /dev/null +++ b/source/atlas-search.txt @@ -0,0 +1,21 @@ +.. _java-atlas-search: + +============ +Atlas Search +============ + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: full text, text analyzer, meta, pipeline, scoring, Lucene + :description: Learn about how to use Atlas Search in the {+driver-long+}. + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +See :atlas:`Atlas Search ` in the MongoDB Atlas documentation. diff --git a/source/atlas-vector-search.txt b/source/atlas-vector-search.txt new file mode 100644 index 000000000..e60a1d487 --- /dev/null +++ b/source/atlas-vector-search.txt @@ -0,0 +1,107 @@ +.. _java-atlas-vector-search: + +=================== +Atlas Vector Search +=================== + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: full text, text analyzer, meta, pipeline, scoring, Lucene, AI, artificial intelligence, code example, semantic, nearest + :description: Learn about how to use Atlas Vector Search in the {+driver-long+}. + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +In this guide, you can learn how to use the :atlas:`Atlas Vector Search +` feature +in the {+driver-short+}. The ``Aggregates`` builders class provides the +the ``vectorSearch()`` helper method that you can use to +create a :atlas:`$vectorSearch ` +pipeline stage. This pipeline stage allows you to perform a **semantic +search** on your documents. A semantic search is a type of search which +locates information that is similar in meaning, but not necessarily +identical, to your provided search term or phrase. + +.. important:: Feature Compatibility + + To learn what versions of MongoDB Atlas support this feature, see + :atlas:`Limitations ` + in the MongoDB Atlas documentation. + +Perform a Vector Search +----------------------- + +To use this feature, you must create a vector search index and index your +vector embeddings. To learn about how to programmatically create a +vector search index, see the :ref:`java-search-indexes` section in the +Indexes guide. To learn more about vector embeddings, see +:atlas:`How to Index Vector Embeddings for Vector Search +` in the Atlas documentation. + +After you create a vector search index on your vector embeddings, you +can reference this index in your pipeline stage, as shown in the +following section. + +Vector Search Example +~~~~~~~~~~~~~~~~~~~~~ + +The following example shows how to build an aggregation pipeline that uses the +``vectorSearch()`` and ``project()`` methods to compute a vector search score: + +.. literalinclude:: /includes/fundamentals/code-snippets/builders/AggBuilders.java + :start-after: // begin vectorSearch + :end-before: // end vectorSearch + :language: java + :dedent: + +.. tip:: Query Vector Type + + The preceding example creates an instance of ``BinaryVector`` to + serve as the query vector, but you can also create a ``List`` of + ``Double`` instances. However, we recommend that you use the + ``BinaryVector`` type to improve storage efficiency. + +The following example shows how you can run the aggregation and print +the vector search meta-score from the result of the preceding +aggregation pipeline: + +.. literalinclude:: /includes/fundamentals/code-snippets/builders/AggBuilders.java + :start-after: // begin vectorSearch-output + :end-before: // end vectorSearch-output + :language: java + :dedent: + +.. tip:: Java Driver Vector Search Examples + + Visit the :atlas:`Atlas documentation ` + to find more tutorials on using the {+driver-short+} to perform Atlas + Vector Searches. + +API Documentation +----------------- + +To learn more about the methods and types mentioned in this +guide, see the following API documentation: + +- `Aggregates.vectorSearch() + <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Aggregates.html#vectorSearch(com.mongodb.client.model.search.FieldSearchPath,java.lang.Iterable,java.lang.String,long,com.mongodb.client.model.search.VectorSearchOptions)>`__ + +- `FieldSearchPath + <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/search/FieldSearchPath.html>`__ + +- `VectorSearchOptions + <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/search/VectorSearchOptions.html>`__ + +- `Projections.metaVectorSearchScore() + <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Projections.html#metaVectorSearchScore(java.lang.String)>`__ + +- `BinaryVector <{+api+}/apidocs/bson/org/bson/BinaryVector.html>`__ \ No newline at end of file diff --git a/source/fundamentals/builders.txt b/source/builders.txt similarity index 93% rename from source/fundamentals/builders.txt rename to source/builders.txt index 631622fa8..1bcd498e3 100644 --- a/source/fundamentals/builders.txt +++ b/source/builders.txt @@ -8,12 +8,12 @@ Builders .. toctree:: - /fundamentals/builders/aggregates - /fundamentals/builders/filters - /fundamentals/builders/indexes - /fundamentals/builders/projections - /fundamentals/builders/sort - /fundamentals/builders/updates + Aggregation + Filters + Indexes + Projection + Sort + Update .. contents:: On this page :local: diff --git a/source/fundamentals/builders/aggregates.txt b/source/builders/aggregates.txt similarity index 99% rename from source/fundamentals/builders/aggregates.txt rename to source/builders/aggregates.txt index 4b9b2b58f..f0c8dd495 100644 --- a/source/fundamentals/builders/aggregates.txt +++ b/source/builders/aggregates.txt @@ -15,6 +15,10 @@ Aggregates Builders :depth: 2 :class: singlecol +.. toctree:: + + Atlas Vector Search + .. _aggregates-builders: Overview @@ -86,7 +90,7 @@ Project Use the ``project()`` method to create a :manual:`$project ` pipeline stage that project specified document fields. Field projection -in aggregation follows the same rules as :doc:`field projection in queries `. +in aggregation follows the same rules as :doc:`field projection in queries `. .. tip:: diff --git a/source/fundamentals/builders/filters.txt b/source/builders/filters.txt similarity index 99% rename from source/fundamentals/builders/filters.txt rename to source/builders/filters.txt index 71ed5a209..2681e9150 100644 --- a/source/fundamentals/builders/filters.txt +++ b/source/builders/filters.txt @@ -20,7 +20,7 @@ In this guide, you can learn how to use **builders** to specify Builders are classes provided by the MongoDB Java driver that help you construct :ref:`BSON ` objects. To learn more, see our :doc:`guide -on builders `. +on builders `. Filters are the operations MongoDB uses to limit your results to what you want to see. diff --git a/source/fundamentals/builders/indexes.txt b/source/builders/indexes.txt similarity index 98% rename from source/fundamentals/builders/indexes.txt rename to source/builders/indexes.txt index cf650829b..888b15f9a 100644 --- a/source/fundamentals/builders/indexes.txt +++ b/source/builders/indexes.txt @@ -16,7 +16,7 @@ Overview -------- In this guide, you can learn how to specify **indexes** using -:doc:`builders ` in the MongoDB Java driver. +:doc:`builders ` in the MongoDB Java driver. The ``Indexes`` builder provides helper methods for constructing the following types of indexes: diff --git a/source/fundamentals/builders/projections.txt b/source/builders/projections.txt similarity index 99% rename from source/fundamentals/builders/projections.txt rename to source/builders/projections.txt index e4e321ca8..f11815add 100644 --- a/source/fundamentals/builders/projections.txt +++ b/source/builders/projections.txt @@ -16,7 +16,7 @@ Overview -------- In this guide, you can learn how to specify **projections** using -:doc:`builders ` in the MongoDB Java driver. +:doc:`builders ` in the MongoDB Java driver. MongoDB supports **field projection**, specifying which fields to include and exclude when returning results from a query. Projection in MongoDB follows some basic rules: diff --git a/source/fundamentals/builders/sort.txt b/source/builders/sort.txt similarity index 96% rename from source/fundamentals/builders/sort.txt rename to source/builders/sort.txt index 59b1e9e97..720d2c07c 100644 --- a/source/fundamentals/builders/sort.txt +++ b/source/builders/sort.txt @@ -32,14 +32,14 @@ examples of sort criteria are: Builders are classes provided by the MongoDB Java driver that help you construct :ref:`BSON ` objects. To learn more, see our :doc:`guide -on builders `. +on builders `. You should read this guide if you would like to use builders to specify sort criteria for your queries. If you want to learn the fundamentals of sorting in the MongoDB Java driver, consider reading our -:doc:`guide on sorting `. +:doc:`guide on sorting `. .. _sorts-builders-sort-sample: @@ -63,7 +63,7 @@ criteria operators supported by MongoDB. These methods return a ``Bson`` object that you can pass to the ``sort()`` method of a ``FindIterable`` instance or to ``Aggregates.sort()``. If you want to learn more about the ``Aggregates`` class, see our -:doc:`guide on the Aggregates builder `. +:doc:`guide on the Aggregates builder `. For more information about the classes and interfaces in this section, see the following API Documentation: @@ -174,7 +174,8 @@ closely a search result matches your search string. To specify a sort by the text score of a text search, use the ``Sorts.metaTextScore()`` static factory method. For a detailed example showing how to specify sort criteria using the ``Sorts.metaTextScore()`` method, see -:ref:`the text search section of our sorting fundamentals guide `. +:ref:`the text search section of our sorting fundamentals guide +`. For more information, see the `Sorts class <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Sorts.html>`__ diff --git a/source/fundamentals/builders/updates.txt b/source/builders/updates.txt similarity index 100% rename from source/fundamentals/builders/updates.txt rename to source/builders/updates.txt diff --git a/source/usage-examples/command.txt b/source/command.txt similarity index 100% rename from source/usage-examples/command.txt rename to source/command.txt diff --git a/source/fundamentals/connection.txt b/source/connection.txt similarity index 70% rename from source/fundamentals/connection.txt rename to source/connection.txt index 6f398ba7d..d34dc63f2 100644 --- a/source/fundamentals/connection.txt +++ b/source/connection.txt @@ -6,14 +6,14 @@ Connection Guide .. toctree:: - /fundamentals/connection/connect - /fundamentals/connection/connection-options - /fundamentals/connection/mongoclientsettings - /fundamentals/connection/network-compression - /fundamentals/connection/tls - /fundamentals/connection/socks - /fundamentals/connection/jndi - Connect to MongoDB Atlas from AWS Lambda + Connect to MongoDB + Connection Options + MongoClient Settings + Stable API + Network Compression + JNDI Datasource + Connection Troubleshooting + AWS Lambda .. contents:: On this page :local: diff --git a/source/fundamentals/connection/connect.txt b/source/connection/connect.txt similarity index 97% rename from source/fundamentals/connection/connect.txt rename to source/connection/connect.txt index 713a350bb..6e122095a 100644 --- a/source/fundamentals/connection/connect.txt +++ b/source/connection/connect.txt @@ -26,9 +26,7 @@ Use the ``MongoClients.create()`` method to construct a ``MongoClient``. As each ``MongoClient`` represents a thread-safe pool of connections to the database, most applications only require a single instance of a - ``MongoClient``, even across multiple threads. To learn more about - how connection pools work in the driver, see the :ref:`FAQ page `. - + ``MongoClient``, even across multiple threads. All resource usage limits, such as max connections, apply to individual ``MongoClient`` instances. diff --git a/source/fundamentals/connection/connection-options.txt b/source/connection/connection-options.txt similarity index 97% rename from source/fundamentals/connection/connection-options.txt rename to source/connection/connection-options.txt index 0ca49b634..517b9b842 100644 --- a/source/fundamentals/connection/connection-options.txt +++ b/source/connection/connection-options.txt @@ -1,3 +1,4 @@ +.. _java-connection-options: .. _connection-options: ================== @@ -122,10 +123,10 @@ parameters of the connection URI to specify the behavior of the client. * - **maxIdleTimeMS** - integer - - Specifies the maximum amount of time, in milliseconds, the Java - driver will allow a pooled connection to idle before closing the + - 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 can allow a pooled collection to be idle. + on how long the driver allows a pooled connection to be idle. | **Default**: ``0`` @@ -193,7 +194,7 @@ parameters of the connection URI to specify the behavior of the client. * - **authMechanism** - string - Specifies the :doc:`authentication mechanism - ` that the driver uses if a credential + ` that the driver uses if a credential was supplied. | **Default**: By default, the client picks the most secure diff --git a/source/connection-troubleshooting.txt b/source/connection/connection-troubleshooting.txt similarity index 70% rename from source/connection-troubleshooting.txt rename to source/connection/connection-troubleshooting.txt index 0c8bd3bc8..a4a79c6bd 100644 --- a/source/connection-troubleshooting.txt +++ b/source/connection/connection-troubleshooting.txt @@ -23,7 +23,14 @@ Connection Troubleshooting .. note:: - Test + This page addresses only connection issues. If you encounter other + issues when using MongoDB or the driver, visit the following resources: + + - The :ref:`Issues & Help ` page for + information about reporting bugs, contributing to the driver, and + finding more resources + - The `MongoDB Community Forums <{+communityForums+}>`__ for + questions, discussions, or general technical support .. replacement:: server-selection-timeout-error @@ -79,7 +86,7 @@ Connection Troubleshooting .. code-block:: java :copyable: false - String uri = "mongodb://:@:/?authSource=users&authMechanism=SCRAM-SHA-256"; + String uri = "mongodb://:@:/?authSource=users&authMechanism=SCRAM-SHA-256"; MongoClient mongoClient = MongoClients.create(uri); .. replacement:: credentials-provider-alternative-method-description @@ -91,7 +98,7 @@ Connection Troubleshooting .. code-block:: java :copyable: false - MongoCredential credential = MongoCredential.createScramSha256Credential("", "", ""); + MongoCredential credential = MongoCredential.createScramSha256Credential("", "", ""); .. replacement:: authentication-guide-reference @@ -108,7 +115,7 @@ Connection Troubleshooting .. code-block:: java :copyable: false - MongoClient mongoClient = MongoClients.create("mongodb://:@:/?authSource=users"); + MongoClient mongoClient = MongoClients.create("mongodb://:@:/?authSource=users"); .. replacement:: dns-resolution-anchor @@ -141,11 +148,6 @@ Connection Troubleshooting ``maxIdleTimeMS`` - .. replacement:: connection-pools-learn-more - - To learn more about how connection pooling works in the driver, see - :ref:`java-faq-connection-pool` in the FAQ. - .. replacement:: scram-failure-error .. code-block:: @@ -204,6 +206,47 @@ Consider setting ``maxConnectionLifeTime`` and maintains a connection to a MongoDB instance. For more information about these parameters, see :ref:`Connection Pool Settings `. +.. _java-server-selection-errors: + +Server Selection Timeout Exceptions +----------------------------------- + +Your application might not be able to complete a request even when some servers +are available, causing the driver to return a server selection timeout +exception. + +This exception is of type ``MongoTimeoutException``. The following +shows a sample of the exception that occurs if you attempt to send a +request to a replica set in which the primary is not reachable: + +.. code-block:: none + + com.mongodb.MongoTimeoutException: + Timed out while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. + Client view of cluster state is + {type=REPLICA_SET, + servers=[ + {address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused}}, + {address=localhost:27018, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused}}, + {address=localhost:27019, type=REPLICA_SET_SECONDARY, roundTripTime=15.0 ms, state=CONNECTED} + ] + } + +The error includes a view of the cluster state that describes the +connection state of each node, which can help you identify the source of +your connection issue. + +In the preceding error, the only connected server, ``localhost:27019``, +is a secondary node. Because of this, the request times out as the +driver is unable to select a server that satisfies the read preference +of ``primary``. In this situation, you can still perform read operations +against the connected secondary node if you set the read preference to +``secondary``, ``secondaryPreferred``, or ``nearest``. + +You can also specify the ``serverSelectionTimeoutMS`` connection option +to adjust the amount of time in which the driver must select a server. To +learn more, see the :ref:`java-connection-options` guide. + .. _java-miscellaneous-errors: Miscellaneous Errors @@ -219,8 +262,10 @@ Monitor Thread Exception INFO: Exception in monitor thread while connecting to server ssc-cluster-01-shard-00-02.9cbnp.mongodb.net:27017 -To resolve this error, you must install certificates as described under -:ref:`Security Certificate Errors `. +This log line indicates that the monitor that continuously +checks the status of each replica set member or ``mongos`` server failed to +contact one of the nodes or servers. This is an expected message during server +maintenance operations and can be safely ignored. Certificate Request Exception ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/source/fundamentals/connection/jndi.txt b/source/connection/jndi.txt similarity index 97% rename from source/fundamentals/connection/jndi.txt rename to source/connection/jndi.txt index 56d66da19..c1e863479 100644 --- a/source/fundamentals/connection/jndi.txt +++ b/source/connection/jndi.txt @@ -1,4 +1,5 @@ .. _jndi: +.. _java-sync-jndi: ============================================= Connect to MongoDB by Using a JNDI Datasource @@ -47,9 +48,7 @@ JNDI Datasource. Add the following ``module.xml`` file into the module: - .. literalinclude:: /includes/fundamentals/code-snippets/wildfly-module-with-version.xml - :language: xml - + .. include:: /includes/fundamentals/code-snippets/wildfly-module-with-version.rst #. Add a binding to the naming subsystem configuration that references the preceding module, the ``MongoClientFactory`` class, and the diff --git a/source/fundamentals/connection/mongoclientsettings.txt b/source/connection/mongoclientsettings.txt similarity index 95% rename from source/fundamentals/connection/mongoclientsettings.txt rename to source/connection/mongoclientsettings.txt index 7bf5fcaf4..154cec5c6 100644 --- a/source/fundamentals/connection/mongoclientsettings.txt +++ b/source/connection/mongoclientsettings.txt @@ -187,7 +187,7 @@ This example demonstrates specifying a ``ConnectionString``: :emphasize-lines: 2,4 MongoClient mongoClient = MongoClients.create( - MongoClientSettings.builder().applyConnectionString(new ConnectionString("mongodb+srv://:@:/?connectTimeoutMS=2000")) + MongoClientSettings.builder().applyConnectionString(new ConnectionString("mongodb+srv://:@:/?connectTimeoutMS=2000")) .applyToSocketSettings(builder -> builder.connectTimeout(5L, SECONDS)) .build()); @@ -259,26 +259,23 @@ settings to modify the driver's behavior: * - ``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. - - .. note:: - - When setting ``srvHost``, the driver does not process any - associated TXT records associated with the host. - - If you want to enable the processing of TXT records, you must - specify the SRV host in the connection string using the - ``applyConnectionString()`` method. - - .. code-block:: java - :emphasize-lines: 3 - - MongoClient mongoClient = MongoClients.create( - MongoClientSettings.builder() - .applyConnectionString(new ConnectionString("mongodb+srv://host1.acme.com"))) + - | 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 diff --git a/source/fundamentals/connection/network-compression.txt b/source/connection/network-compression.txt similarity index 97% rename from source/fundamentals/connection/network-compression.txt rename to source/connection/network-compression.txt index ef319ff22..76390f1e5 100644 --- a/source/fundamentals/connection/network-compression.txt +++ b/source/connection/network-compression.txt @@ -53,7 +53,7 @@ connection string using ``ConnectionString`` or by calling the method in the .. code-block:: java - ConnectionString connectionString = new ConnectionString("mongodb+srv://:@/?compressors=snappy,zlib,zstd"); + ConnectionString connectionString = new ConnectionString("mongodb+srv://:@/?compressors=snappy,zlib,zstd"); MongoClient mongoClient = MongoClients.create(connectionString); Specify compression algorithms using the following strings: diff --git a/source/fundamentals/stable-api.txt b/source/connection/stable-api.txt similarity index 100% rename from source/fundamentals/stable-api.txt rename to source/connection/stable-api.txt diff --git a/source/crud.txt b/source/crud.txt new file mode 100644 index 000000000..f64c94fe0 --- /dev/null +++ b/source/crud.txt @@ -0,0 +1,28 @@ +.. _java-crud-operations: + +=============== +CRUD Operations +=============== + +.. toctree:: + :caption: CRUD Operations + + Read + Write + Query + Compound Operations + Transactions + 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. diff --git a/source/fundamentals/collations.txt b/source/crud/collations.txt similarity index 99% rename from source/fundamentals/collations.txt rename to source/crud/collations.txt index 3cac66424..1c2d8dcd4 100644 --- a/source/fundamentals/collations.txt +++ b/source/crud/collations.txt @@ -1,9 +1,9 @@ +.. _java-crud-collations: + ========== Collations ========== -.. default-domain:: mongodb - .. contents:: On this page :local: :backlinks: none @@ -65,7 +65,6 @@ order as shown below: coté côté - .. _collations-specify: How to Specify Collations @@ -536,4 +535,3 @@ see the following API Documentation: - `Accumulators <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Accumulators.html>`__ - `Aggregates <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Aggregates.html>`__ - `Sorts <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Sorts.html>`__ - diff --git a/source/fundamentals/crud/compound-operations.txt b/source/crud/compound-operations.txt similarity index 96% rename from source/fundamentals/crud/compound-operations.txt rename to source/crud/compound-operations.txt index 9cc4277fc..d8c7a0b86 100644 --- a/source/fundamentals/crud/compound-operations.txt +++ b/source/crud/compound-operations.txt @@ -1,3 +1,5 @@ +.. _java-compound-operations: + =================== Compound Operations =================== @@ -101,10 +103,10 @@ The output of the preceding code resembles the following: {"food": "pizza", "color": "green"} For more information about the ``Projections`` class, see our -:doc:`guide on the Projections builder `. +:doc:`guide on the Projections builder `. For more information about the upsert operation, see our -:doc:`guide on upserts `. +:doc:`guide on upserts `. For more information about the methods and classes mentioned in this section, see the following API Documentation: @@ -187,7 +189,7 @@ The output of the preceding code resembles the following: {"_id": 2, "food": "pear", "color": "yellow"} For more information about the ``Sorts`` class, see our -:doc:`guide on the Sorts builder `. +:doc:`guide on the Sorts builder `. For more information about the methods and classes mentioned in this section, see the following API Documentation: @@ -318,10 +320,10 @@ instance: for the duration of your compound operation. For information on the ``Updates`` class, see our -:doc:`guide on the Updates builder `. +:doc:`guide on the Updates builder `. For more information of the ``Filters`` class, see our -:doc:`guide on the Filters builder `. +:doc:`guide on the Filters builder `. For more information about the ``findOneAndUpdate()`` method, see the API Documentation for the `MongoCollection class <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#findOneAndUpdate(org.bson.conversions.Bson,java.util.List,com.mongodb.client.model.FindOneAndUpdateOptions)>`__. diff --git a/source/fundamentals/gridfs.txt b/source/crud/gridfs.txt similarity index 94% rename from source/fundamentals/gridfs.txt rename to source/crud/gridfs.txt index 4777e2803..b98cfb28f 100644 --- a/source/fundamentals/gridfs.txt +++ b/source/crud/gridfs.txt @@ -1,8 +1,17 @@ -====== -GridFS -====== +.. _java-crud-gridfs: + +============================== +Large File Storage with GridFS +============================== .. default-domain:: mongodb +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: retrieve, size limit + :description: Store large files with GridFS in the {+driver-long+}. .. contents:: On this page :local: @@ -133,6 +142,16 @@ following code snippet: See the `GridFSUploadOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/gridfs/model/GridFSUploadOptions.html>`__ API Documentation for more information. +.. important:: Use a ``MAJORITY`` Write Concern + + When storing files in a GridFS bucket, ensure that you use the ``WriteConcern.MAJORITY`` + write concern. If you specify a different write concern, replica set elections that occur + during a GridFS file upload might interrupt the upload process and cause some file chunks + to be lost. + + For more information about write concerns, see the :manual:`Write Concern ` + page in the Server manual. + Upload a File Using an Input Stream ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -247,8 +266,8 @@ see the following resources: - `GridFSFindIterable <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/gridfs/GridFSFindIterable.html>`__ API Documentation - `GridFSBucket.find() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/gridfs/GridFSBucket.html#find(org.bson.conversions.Bson)>`__ API Documentation -- :doc:`Sort Results ` -- :doc:`Limit the Number of Returned Results ` +- :doc:`Sort Results ` +- :doc:`Limit the Number of Returned Results ` .. _gridfs-download-files: diff --git a/source/fundamentals/crud/query-document.txt b/source/crud/query-document.txt similarity index 100% rename from source/fundamentals/crud/query-document.txt rename to source/crud/query-document.txt diff --git a/source/crud/read-operations.txt b/source/crud/read-operations.txt new file mode 100644 index 000000000..1c9183ea0 --- /dev/null +++ b/source/crud/read-operations.txt @@ -0,0 +1,29 @@ +.. _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 + Data from a Cursor + Sort Results + Skip Returned Results + Limit Returned Results + Specify Fields to Return + Geospatial Data + Search Text + +- :doc:`/crud/read-operations/retrieve` +- :doc:`/crud/read-operations/cursor` +- :doc:`/crud/read-operations/sort` +- :doc:`/crud/read-operations/skip` +- :doc:`/crud/read-operations/limit` +- :doc:`/crud/read-operations/project` +- :doc:`/crud/read-operations/geo` +- :doc:`/crud/read-operations/text` diff --git a/source/fundamentals/crud/read-operations/cursor.txt b/source/crud/read-operations/cursor.txt similarity index 100% rename from source/fundamentals/crud/read-operations/cursor.txt rename to source/crud/read-operations/cursor.txt diff --git a/source/fundamentals/crud/read-operations/geo.txt b/source/crud/read-operations/geo.txt similarity index 97% rename from source/fundamentals/crud/read-operations/geo.txt rename to source/crud/read-operations/geo.txt index a0f5f400e..58f7e8e57 100644 --- a/source/fundamentals/crud/read-operations/geo.txt +++ b/source/crud/read-operations/geo.txt @@ -98,7 +98,7 @@ GeoJSON data to a ``2dsphere`` index. The following snippet creates a collection.createIndex(Indexes.geo2dsphere("location.geo")); For more information about the ``Indexes`` builder, see our -:doc:`guide on the Indexes builder `. +:doc:`guide on the Indexes builder `. .. guide resource @@ -131,7 +131,7 @@ legacy coordinate pairs to a ``2d`` index. The following snippet creates a collection.createIndex(Indexes.geo2d("coordinates")); For more information about the ``Indexes`` builder, see our -:doc:`guide on the Indexes builder `. +:doc:`guide on the Indexes builder `. For more information about legacy coordinate pairs, see the :manual:`{+mdb-server+} manual page on legacy coordinate pairs `. @@ -173,7 +173,7 @@ For more information about geospatial query operators, see the .. external resource For more information about ``Filters``, see our -:doc:`guide on the Filters builder `. +:doc:`guide on the Filters builder `. Query Parameters ~~~~~~~~~~~~~~~~ @@ -258,7 +258,7 @@ For more information about the ``$near`` operator, see :manual:`the reference documentation for $near `. For more information about ``Filters``, -:doc:`see our guide on the Filters builder `. +:doc:`see our guide on the Filters builder `. Query Within a Range ~~~~~~~~~~~~~~~~~~~~ diff --git a/source/fundamentals/crud/read-operations/limit.txt b/source/crud/read-operations/limit.txt similarity index 98% rename from source/fundamentals/crud/read-operations/limit.txt rename to source/crud/read-operations/limit.txt index cac0b5f8f..49d384106 100644 --- a/source/fundamentals/crud/read-operations/limit.txt +++ b/source/crud/read-operations/limit.txt @@ -25,7 +25,7 @@ to reach the specified limit, it can return a smaller number. If you use ``limit()`` with the ``skip()`` instance method, the skip applies first and the limit only applies to the documents left over after the skip. For more information about the ``skip()`` method, see our -:doc:`guide on Skipping Returned Documents `. +:doc:`guide on Skipping Returned Documents `. The following examples demonstrate, respectively, how to insert data into a collection, how to use ``limit()`` to restrict the number of returned documents, diff --git a/source/fundamentals/crud/read-operations/project.txt b/source/crud/read-operations/project.txt similarity index 100% rename from source/fundamentals/crud/read-operations/project.txt rename to source/crud/read-operations/project.txt diff --git a/source/fundamentals/crud/read-operations/retrieve.txt b/source/crud/read-operations/retrieve.txt similarity index 98% rename from source/fundamentals/crud/read-operations/retrieve.txt rename to source/crud/read-operations/retrieve.txt index 806e60b91..02dba978d 100644 --- a/source/fundamentals/crud/read-operations/retrieve.txt +++ b/source/crud/read-operations/retrieve.txt @@ -54,7 +54,7 @@ To perform a find operation, call the ``find()`` method on an instance of a ``MongoCollection``. This method searches a collection for documents that match the query filter you provide. For more information about how to specify a query, see our :doc:`Specify a Query -` guide. +` guide. Example ~~~~~~~ @@ -71,7 +71,7 @@ To address this scenario, the owner finds orders to match the criteria: :end-before: end findExample For more information about how to build filters, see our :doc:`Filters Builders -` guide. +` guide. The following shows the output of the preceding query: diff --git a/source/fundamentals/crud/read-operations/skip.txt b/source/crud/read-operations/skip.txt similarity index 100% rename from source/fundamentals/crud/read-operations/skip.txt rename to source/crud/read-operations/skip.txt diff --git a/source/fundamentals/crud/read-operations/sort.txt b/source/crud/read-operations/sort.txt similarity index 98% rename from source/fundamentals/crud/read-operations/sort.txt rename to source/crud/read-operations/sort.txt index aa31654bb..b10b5e801 100644 --- a/source/fundamentals/crud/read-operations/sort.txt +++ b/source/crud/read-operations/sort.txt @@ -97,7 +97,7 @@ builder class. While it is possible to specify sort criteria using any class that implements the ``Bson`` interface, we recommend that you specify sort criteria through the ``Sorts`` builder. For more information about the ``Sorts`` builder class, see our -:doc:`guide on the Sorts builder `. +:doc:`guide on the Sorts builder `. For more information about the classes and interfaces in this section, see the following API Documentation: @@ -304,6 +304,7 @@ in the following order: {"_id": 3, "letter": "a", "food": "maple syrup"} {"_id": 5, "letter": "a", "food": "milk and cookies"} +.. _java-sync-sorts-crud-text-search: .. _sorts-crud-text-search: Text Search @@ -328,9 +329,9 @@ sort by the text score. In the following code example, we show how you can use the ``Sorts.metaTextScore()`` method to sort the results of a text search on the :ref:`sample collection `. -The code example uses the :doc:`Filters `, -:doc:`Indexes `, and -:doc:`Projections ` builders. +The code example uses the :doc:`Filters `, +:doc:`Indexes `, and +:doc:`Projections ` builders. The code example performs the following actions: #. Creates a text index for your diff --git a/source/fundamentals/crud/read-operations/text.txt b/source/crud/read-operations/text.txt similarity index 97% rename from source/fundamentals/crud/read-operations/text.txt rename to source/crud/read-operations/text.txt index 8dc7b200b..289398744 100644 --- a/source/fundamentals/crud/read-operations/text.txt +++ b/source/crud/read-operations/text.txt @@ -31,7 +31,7 @@ text searches: - Search Text with Terms Excluded If you want to sort your text search results, see the :ref:`Text Search -` section of our Sort Results guide. +` section of our Sort Results guide. Sample Documents ~~~~~~~~~~~~~~~~ @@ -83,7 +83,7 @@ Text Search Use the ``Filters.text()`` method to specify a text search. The ``Filters.text()`` method uses the :doc:`Filters builder -` to define a query filter specifying +` to define a query filter specifying what to search for during the text search. The query filter is represented by a :ref:`BSON ` instance. Pass the query filter to the ``find()`` method to run a text search. @@ -92,7 +92,7 @@ When you execute the ``find()`` method, MongoDB runs a text search on all the fields indexed with the text index on the collection. MongoDB returns documents that contain one or more of the search terms and a relevance score for each result. For more information about relevance -scores, see the :ref:`Text Search ` section in +scores, see the :ref:`Text Search ` section in our Sort Results guide. Specify Options diff --git a/source/crud/transactions.txt b/source/crud/transactions.txt new file mode 100644 index 000000000..352b6ad02 --- /dev/null +++ b/source/crud/transactions.txt @@ -0,0 +1,154 @@ +.. _java-fundamentals-transactions: + +============ +Transactions +============ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: ACID, write, consistency, code example + +Overview +-------- + +In this guide, you can learn how to use the {+driver-short+} to perform +**transactions**. :manual:`Transactions ` allow +you to run a series of operations that do not change any data until the +transaction is committed. If any operation in the transaction returns an +error, the driver cancels the transaction and discards all data changes +before they ever become visible. + +In MongoDB, transactions run within logical **sessions**. A +:manual:`session ` is a grouping of related +read or write operations that you intend to run sequentially. Sessions +enable :manual:`causal consistency +` for a +group of operations or allow you to execute operations in an +:website:`ACID transaction `. MongoDB +guarantees that the data involved in your transaction operations remains +consistent, even if the operations encounter unexpected errors. + +When using the {+driver-short+}, you can create a new session from a +``MongoClient`` instance as a ``ClientSession`` type. We recommend that you reuse +your client for multiple sessions and transactions instead of +instantiating a new client each time. + +.. warning:: + + Use a ``ClientSession`` only with the ``MongoClient`` (or associated + ``MongoDatabase`` or ``MongoCollection``) that created it. Using a + ``ClientSession`` with a different ``MongoClient`` results in operation + errors. + +.. important:: + + You must include the ``session`` as a parameter for any operations that you + want to include in a transaction. + +Methods +------- + +Create a ``ClientSession`` by using the ``startSession()`` method on your +``MongoClient`` instance. You can then modify the session state by using the +methods provided by the ``ClientSession``. The following table describes the +methods you can use to manage your transaction: + +.. list-table:: + :widths: 25 75 + :header-rows: 1 + + * - Method + - Description + + * - ``startTransaction()`` + - | Starts a new transaction for this session with the + default transaction options. Pass an instance of ``TransactionOptions`` + as a parameter to start a transaction with given options. You + cannot start a transaction if there's already an active transaction + running in the session. + | + | **Parameter**: ``TransactionOptions transactionOptions`` + + * - ``abortTransaction()`` + - | Ends the active transaction for this session. Returns an error + if there is no active transaction for the + session or the transaction was previously ended. + + * - ``commitTransaction()`` + - | Commits the active transaction for this session. Returns an + error if there is no active transaction for the session or if the + transaction was ended. + + * - ``withTransaction()`` + - | Starts a new transaction for this session and runs the given function. This + method handles retries, committing, and aborting transactions. Pass an + instance of ``TransactionBody`` as a parameter that defines the + operations you want to execute within the transaction. + | + | **Parameter**: ``TransactionBody transactionBody`` + +A ``ClientSession`` also has methods to retrieve session properties and modify mutable +session properties. View the :ref:`API +documentation ` to learn more about these methods. + +Example +------- + +The following example demonstrates how you can create a session, create a transaction, +and commit a multi-document insert operation through the following steps: + +1. Create a session from the client by using the ``startSession()`` method. +#. Set transaction options to configure transaction behavior. +#. Use the ``withTransaction()`` method to start a transaction. +#. Insert multiple documents. The ``withTransaction()`` method executes, commits, and aborts + the transaction. If any operation results in errors, ``withTransaction()`` handles canceling + the transaction. + +.. literalinclude:: /includes/fundamentals/code-snippets/Transaction.java + :language: java + :dedent: + :start-after: start transaction + :end-before: end transaction + +If you require more control over your transactions, you can use the ``startTransaction()`` +method. You can use this method with the ``commitTransaction()`` and ``abortTransaction()`` +methods described in the preceding section to manually manage the transaction lifecycle. + +Additional Information +---------------------- + +To learn more about the concepts mentioned in this guide, see the following pages in +the Server manual: + +- :manual:`Transactions ` +- :manual:`Server Sessions ` +- :manual:`Read Isolation, Consistency, and Recency ` + +To learn more about ACID compliance, see the :website:`What are ACID +Properties in Database Management Systems? ` +article on the MongoDB website. + +.. _api-docs-transaction: + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the types or methods discussed in this +guide, see the following API Documentation: + +- `ClientSession <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html>`_ +- `startTransaction <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html#startTransaction()>`_ +- `commitTransaction <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html#commitTransaction()>`_ +- `abortTransaction <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html#abortTransaction()>`_ +- `withTransaction <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html#withTransaction(com.mongodb.client.TransactionBody)>`_ +- `TransactionOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/TransactionOptions.html>`_ + \ No newline at end of file diff --git a/source/crud/write-operations.txt b/source/crud/write-operations.txt new file mode 100644 index 000000000..aa0b2d86a --- /dev/null +++ b/source/crud/write-operations.txt @@ -0,0 +1,25 @@ +.. _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/fundamentals/crud/write-operations/bulk.txt b/source/crud/write-operations/bulk.txt similarity index 100% rename from source/fundamentals/crud/write-operations/bulk.txt rename to source/crud/write-operations/bulk.txt diff --git a/source/fundamentals/crud/write-operations/delete.txt b/source/crud/write-operations/delete.txt similarity index 100% rename from source/fundamentals/crud/write-operations/delete.txt rename to source/crud/write-operations/delete.txt diff --git a/source/fundamentals/crud/write-operations/embedded-arrays.txt b/source/crud/write-operations/embedded-arrays.txt similarity index 98% rename from source/fundamentals/crud/write-operations/embedded-arrays.txt rename to source/crud/write-operations/embedded-arrays.txt index bde25f636..0a9c2d921 100644 --- a/source/fundamentals/crud/write-operations/embedded-arrays.txt +++ b/source/crud/write-operations/embedded-arrays.txt @@ -39,7 +39,7 @@ The examples on this page use the ``findOneAndUpdate()`` method of the example uses an instance of the ``FindOneAndUpdateOptions`` class to have MongoDB retrieve the document after the update occurs. For more information on the ``findOneAndUpdate()`` method, see our -:doc:`Compound Operations guide `. +:doc:`Compound Operations guide `. Specifying an Update -------------------- diff --git a/source/fundamentals/crud/write-operations/insert.txt b/source/crud/write-operations/insert.txt similarity index 98% rename from source/fundamentals/crud/write-operations/insert.txt rename to source/crud/write-operations/insert.txt index 5bedc1340..39a4c8051 100644 --- a/source/fundamentals/crud/write-operations/insert.txt +++ b/source/crud/write-operations/insert.txt @@ -30,7 +30,7 @@ methods. The following sections focus on ``insertOne()`` and ``insertMany()``. For information on how to use the ``bulkWrite()`` method, see our -:doc:`guide on Bulk Operations `. +:doc:`guide on Bulk Operations `. A Note About ``_id`` -------------------- diff --git a/source/fundamentals/crud/write-operations/modify.txt b/source/crud/write-operations/modify.txt similarity index 97% rename from source/fundamentals/crud/write-operations/modify.txt rename to source/crud/write-operations/modify.txt index 42c4f6081..991066be2 100644 --- a/source/fundamentals/crud/write-operations/modify.txt +++ b/source/crud/write-operations/modify.txt @@ -118,7 +118,7 @@ The following shows the updated documents in the ``paint_inventory`` collection: If zero documents match the query filter in the update operation, ``updateMany()`` makes no changes to documents in the collection. See -our :doc:`upsert guide ` to +our :doc:`upsert guide ` to learn how to insert a new document instead of updating one if no documents match. @@ -194,7 +194,7 @@ The following shows the updated document: If zero documents match the query filter in the replace operation, ``replaceOne()`` makes no changes to documents in the collection. See -our :doc:`upsert guide ` to +our :doc:`upsert guide ` to learn how to insert a new document instead of replacing one if no documents match. diff --git a/source/fundamentals/crud/write-operations/upsert.txt b/source/crud/write-operations/upsert.txt similarity index 100% rename from source/fundamentals/crud/write-operations/upsert.txt rename to source/crud/write-operations/upsert.txt diff --git a/source/data-formats.txt b/source/data-formats.txt new file mode 100644 index 000000000..f553fbc97 --- /dev/null +++ b/source/data-formats.txt @@ -0,0 +1,26 @@ +============ +Data Formats +============ + +.. meta:: + :description: Learn how to convert between MongoDB and Java data formats by using the {+driver-long+}. + +.. toctree:: + :caption: Data Formats + + BSON + Extended JSON + Documents + POJOs + POJO Customization + Records + Codecs + Time Series Collections + +- :doc:`/data-formats/document-data-format-bson` +- :doc:`/data-formats/document-data-format-extended-json` +- :doc:`/data-formats/documents` +- :doc:`/data-formats/document-data-format-pojo` +- :doc:`/data-formats/document-data-format-record` +- :doc:`/data-formats/pojo-customization` +- :doc:`/data-formats/codecs` diff --git a/source/fundamentals/data-formats/codecs.txt b/source/data-formats/codecs.txt similarity index 99% rename from source/fundamentals/data-formats/codecs.txt rename to source/data-formats/codecs.txt index ecb4ea416..786532da7 100644 --- a/source/fundamentals/data-formats/codecs.txt +++ b/source/data-formats/codecs.txt @@ -176,7 +176,7 @@ from the prior example using the following code: .. code-block:: java :copyable: true - Codec powerStatusCodec = codecRegistry.get(String.class); + Codec powerStatusCodec = codecRegistry.get(PowerStatus.class); Codec integerCodec = codecRegistry.get(Integer.class); If you attempt to retrieve a ``Codec`` instance for a class that is not diff --git a/source/fundamentals/data-formats/document-data-format-bson.txt b/source/data-formats/document-data-format-bson.txt similarity index 100% rename from source/fundamentals/data-formats/document-data-format-bson.txt rename to source/data-formats/document-data-format-bson.txt diff --git a/source/fundamentals/data-formats/document-data-format-extended-json.txt b/source/data-formats/document-data-format-extended-json.txt similarity index 100% rename from source/fundamentals/data-formats/document-data-format-extended-json.txt rename to source/data-formats/document-data-format-extended-json.txt diff --git a/source/fundamentals/data-formats/document-data-format-pojo.txt b/source/data-formats/document-data-format-pojo.txt similarity index 100% rename from source/fundamentals/data-formats/document-data-format-pojo.txt rename to source/data-formats/document-data-format-pojo.txt diff --git a/source/fundamentals/data-formats/document-data-format-record.txt b/source/data-formats/document-data-format-record.txt similarity index 100% rename from source/fundamentals/data-formats/document-data-format-record.txt rename to source/data-formats/document-data-format-record.txt diff --git a/source/fundamentals/data-formats/documents.txt b/source/data-formats/documents.txt similarity index 90% rename from source/fundamentals/data-formats/documents.txt rename to source/data-formats/documents.txt index 5fe6a98aa..58e9146e9 100644 --- a/source/fundamentals/data-formats/documents.txt +++ b/source/data-formats/documents.txt @@ -116,11 +116,15 @@ different field types: Document author = new Document("_id", new ObjectId()) .append("name", "Gabriel García Márquez") - .append("dateOfDeath", Date.from(LocalDate.of(2014, 4, 17).atStartOfDay(ZoneId.systemDefault()).toInstant())) + .append("dateOfDeath", + Date.from(LocalDate.of(2014, 4, 17).atStartOfDay(ZoneId.systemDefault()).toInstant())) .append("novels", Arrays.asList( - new Document("title", "One Hundred Years of Solitude").append("yearPublished", 1967), - new Document("title", "Chronicle of a Death Foretold").append("yearPublished", 1981), - new Document("title", "Love in the Time of Cholera").append("yearPublished", 1985))); + new Document("title", "One Hundred Years of Solitude") + .append("yearPublished", 1967), + new Document("title", "Chronicle of a Death Foretold") + .append("yearPublished", 1981), + new Document("title", "Love in the Time of Cholera") + .append("yearPublished", 1985))); To insert this document into a collection, instantiate a collection using the ``getCollection()`` method and call the :doc:`insertOne @@ -228,11 +232,16 @@ different field types: BsonDocument author = new BsonDocument() .append("_id", new BsonObjectId()) .append("name", new BsonString("Gabriel García Márquez")) - .append("dateOfDeath", new BsonDateTime(LocalDate.of(2014, 4, 17).atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli())) + .append("dateOfDeath", + new BsonDateTime(LocalDate.of(2014, 4, 17).atStartOfDay(ZoneId.systemDefault()) + .toInstant().toEpochMilli())) .append("novels", new BsonArray(Arrays.asList( - new BsonDocument().append("title", new BsonString("One Hundred Years of Solitude")).append("yearPublished", new BsonInt32(1967)), - new BsonDocument().append("title", new BsonString("Chronicle of a Death Foretold")).append("yearPublished", new BsonInt32(1981)), - new BsonDocument().append("title", new BsonString("Love in the Time of Cholera")).append("yearPublished", new BsonInt32(1985)) + new BsonDocument().append("title", new BsonString("One Hundred Years of Solitude")) + .append("yearPublished", new BsonInt32(1967)), + new BsonDocument().append("title", new BsonString("Chronicle of a Death Foretold")) + .append("yearPublished", new BsonInt32(1981)), + new BsonDocument().append("title", new BsonString("Love in the Time of Cholera")) + .append("yearPublished", new BsonInt32(1985)) ))); To insert this document into a collection, instantiate a collection @@ -359,7 +368,11 @@ The output of the preceding code resembles the following: .. code-block:: none :copyable: false - query result in extended json format: {"_id": {"$oid": "6035210f35bd203721c3eab8"}, "name": "Gabriel García Márquez", "dateOfDeath": {"$date": "2014-04-17T04:00:00Z"}, "novels": [{"title": "One Hundred Years of Solitude", "yearPublished": 1967}, {"title": "Chronicle of a Death Foretold", "yearPublished": 1981}, {"title": "Love in the Time of Cholera", "yearPublished": 1985}]} + query result in extended json format: {"_id": {"$oid": "6035210f35bd203721c3eab8"}, + "name": "Gabriel García Márquez", "dateOfDeath": {"$date": "2014-04-17T04:00:00Z"}, + "novels": [{"title": "One Hundred Years of Solitude", "yearPublished": 1967}, + {"title": "Chronicle of a Death Foretold", "yearPublished": 1981}, + {"title": "Love in the Time of Cholera", "yearPublished": 1985}]} .. tip:: @@ -394,7 +407,8 @@ The output of the preceding code resembles the following: JsonObject author = new JsonObject("{\"_id\": \"6035210f35bd203721c3eab8\", " + "\"name\": \"Gabriel García Márquez\", " + "\"dateOfDeath\": {\"$date\": \"2014-04-17T04:00:00Z\"}, " - + "\"novels\": [{\"title\": \"One Hundred Years of Solitude\", \"yearPublished\": 1967}, {\"title\": \"Chronicle of a Death Foretold\", \"yearPublished\": 1981}, " + + "\"novels\": [{\"title\": \"One Hundred Years of Solitude\", \"yearPublished\": 1967}, + {\"title\": \"Chronicle of a Death Foretold\", \"yearPublished\": 1981}, " + "{\"title\": \"Love in the Time of Cholera\", \"yearPublished\": 1985}]}\n"); collection.insertOne(author); JsonObject query = new JsonObject("{\"name\": \"Gabriel Garc\\u00eda M\\u00e1rquez\"}"); @@ -408,7 +422,10 @@ The output of the preceding code resembles the following: .. code-block:: none :copyable: false - query result in relaxed json format: {"_id": "6035210f35bd203721c3eab8", "name": "Gabriel García Márquez", "dateOfDeath": {"$date": "2014-04-17T04:00:00Z"}, "novels": [{"title": "One Hundred Years of Solitude", "yearPublished": 1967}, {"title": "Chronicle of a Death Foretold", "yearPublished": 1981}, {"title": "Love in the Time of Cholera", "yearPublished": 1985}]} + query result in relaxed json format: {"_id": "6035210f35bd203721c3eab8", "name": "Gabriel García Márquez", + "dateOfDeath": {"$date": "2014-04-17T04:00:00Z"}, "novels": [{"title": "One Hundred Years of Solitude", + "yearPublished": 1967}, {"title": "Chronicle of a Death Foretold", "yearPublished": 1981}, + {"title": "Love in the Time of Cholera", "yearPublished": 1985}]} For more information about the methods and classes mentioned in this section, see the following API Documentation: @@ -442,11 +459,15 @@ different field types: BasicDBObject author = new BasicDBObject("_id", new ObjectId()) .append("name", "Gabriel García Márquez") - .append("dateOfDeath", Date.from(LocalDate.of(2014, 4, 17).atStartOfDay(ZoneId.systemDefault()).toInstant())) + .append("dateOfDeath", Date.from(LocalDate.of(2014, 4, 17) + .atStartOfDay(ZoneId.systemDefault()).toInstant())) .append("novels", Arrays.asList( - new BasicDBObject("title", "One Hundred Years of Solitude").append("yearPublished", 1967), - new BasicDBObject("title", "Chronicle of a Death Foretold").append("yearPublished", 1981), - new BasicDBObject("title", "Love in the Time of Cholera").append("yearPublished", 1985))); + new BasicDBObject("title", "One Hundred Years of Solitude") + .append("yearPublished", 1967), + new BasicDBObject("title", "Chronicle of a Death Foretold") + .append("yearPublished", 1981), + new BasicDBObject("title", "Love in the Time of Cholera") + .append("yearPublished", 1985))); To insert this document into a collection, instantiate a collection using the ``getCollection()`` method specifying the ``BasicDBObject`` class as @@ -470,7 +491,8 @@ data from the collection using the following code: import com.mongodb.client.model.Filters; // - BasicDBObject doc = collection.find(Filters.eq("name", "Gabriel García Márquez")).first(); + BasicDBObject doc = + collection.find(Filters.eq("name", "Gabriel García Márquez")).first(); if (doc != null) { System.out.println("_id: " + doc.getObjectId("_id") + ", name: " + doc.getString("name") diff --git a/source/fundamentals/data-formats/pojo-customization.txt b/source/data-formats/pojo-customization.txt similarity index 88% rename from source/fundamentals/data-formats/pojo-customization.txt rename to source/data-formats/pojo-customization.txt index 7cfe25cc8..ea54ddce4 100644 --- a/source/fundamentals/data-formats/pojo-customization.txt +++ b/source/data-formats/pojo-customization.txt @@ -285,7 +285,7 @@ package: * - ``BsonRepresentation`` - Specifies the BSON type used to store the value when different from the - POJO property. + POJO property. See an example of :ref:`bsonrepresentation-annotation-code-example` on this page. * - ``BsonId`` - Marks a property to serialize as the _id property. @@ -295,22 +295,24 @@ package: and/or deserialize a property. * - ``BsonProperty`` - - Specifies a custom document field name when converting the POJO - field to BSON. You can include a discriminator to serialize POJOs - nested within the field. + - | Specifies a custom document field name when converting the POJO + field to BSON. You can include a discriminator to serialize POJOs + nested within the field. + | + | When applying ``@BsonProperty`` to a private field, + **you must also add getter and setter methods for that field to serialize and + customize the field name**. - * - ``BsonExtraElements`` - - Specifies the POJO field on which to deserialize all elements that are - not mapped to a field. The POJO field must be one of the following - types: - - - `Document <{+api+}/apidocs/bson/org/bson/Document.html>`__ - - `BsonDocument <{+api+}/apidocs/bson/org/bson/BsonDocument.html>`__ - - ``Map`` - - .. seealso:: - :ref:`BsonExtraElements Annotation Example ` + * - ``BsonExtraElements`` + - | Specifies the POJO field on which to deserialize all elements that are + not mapped to a field. The POJO field must be one of the following + types: + | - `Document <{+api+}/apidocs/bson/org/bson/Document.html>`__ + | - `BsonDocument <{+api+}/apidocs/bson/org/bson/BsonDocument.html>`__ + | - ``Map`` + | + | See an example of a :ref:`BsonExtraElements Annotation Example `. The following code snippet shows a sample POJO called ``Product`` that uses several of the preceding annotations. @@ -344,9 +346,16 @@ several of the preceding annotations. public Product(@BsonProperty("modelName") String name) { this.name = name; } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } // ... - } .. _bson-annotation-convention: @@ -374,7 +383,6 @@ The annotations in the example POJO specify the following behavior: - Omit the ``relatedItems`` field and value when converting data - Use the ``Product(String name)`` constructor when instantiating the POJO - .. _bsonextraelements-annotation-code-example: BsonExtraElements Example @@ -441,6 +449,59 @@ following data: additionalInfo=Document{{dimensions=3x4x5, weight=256g}} ] +.. _bsonrepresentation-annotation-code-example: + +BsonRepresentation Error Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The ``@BsonRepresentation`` annotation allows you to store a POJO class field +as a different data type in your MongoDB database. The :ref:`Product POJO +` code example in the :ref:`annotations` section +of this page uses ``@BsonRepresentation`` to store ``String`` values as +``ObjectId`` values in the database documents. + +However, using the ``@BsonRepresentation`` annotation to convert between data types other +than ``String`` and ``ObjectId`` causes the following error message: + +.. code-block:: + :copyable: false + + Codec must implement RepresentationConfigurable to support BsonRepresentation + +For example, the following code adds a ``purchaseDate`` field of type ``Long`` to the +``Product`` POJO. This example attempts to use ``@BsonRepresentation`` to represent ``Long`` +values as ``DateTime`` values in the database: + +.. code-block:: java + :emphasize-lines: 9-10 + + public class Product { + @BsonProperty("modelName") + private String name; + + @BsonId() + @BsonRepresentation(BsonType.OBJECT_ID) + private String serialNumber; + + @BsonRepresentation(BsonType.DATE_TIME) + private Long purchaseDate; + + // ... + } + +The preceding code results in an error. Instead, you can create a custom Codec to +convert the ``purchaseDate`` values from type ``Long`` to ``DateTime``: + +.. literalinclude:: /includes/fundamentals/code-snippets/LongRepresentableCodec.java + :language: java + :start-after: start class + :end-before: end class + +Then, add an instance of the ``LongRepresentableCodec`` to your ``CodecRegistry``, which contains +a mapping between your Codec and the Java object type to which it applies. For instructions +on registering your custom Codec with the ``CodecRegistry``, see the :ref:`fundamentals-codecs` +guide. + .. _pojo-discriminators: Discriminators @@ -699,4 +760,3 @@ codec registry. See the documentation on the :ref:`default codec registry ` For more information about how to register the codecs it includes. - diff --git a/source/fundamentals/time-series.txt b/source/data-formats/time-series.txt similarity index 97% rename from source/fundamentals/time-series.txt rename to source/data-formats/time-series.txt index fb963c114..dc485ba37 100644 --- a/source/fundamentals/time-series.txt +++ b/source/data-formats/time-series.txt @@ -95,7 +95,7 @@ Query a Time Series Collection ------------------------------ To query in a time series collection, use the same conventions as you -would for :doc:`retrieving ` +would for :doc:`retrieving ` and :ref:`aggregating data `. .. note:: Window Functions diff --git a/source/fundamentals/databases-collections.txt b/source/databases-collections.txt similarity index 99% rename from source/fundamentals/databases-collections.txt rename to source/databases-collections.txt index 30ffcedbb..e6c21a808 100644 --- a/source/fundamentals/databases-collections.txt +++ b/source/databases-collections.txt @@ -1,3 +1,5 @@ +.. _java-sync-databases-collections: + ========================= Databases and Collections ========================= diff --git a/source/fundamentals.txt b/source/fundamentals.txt deleted file mode 100644 index 691fcda85..000000000 --- a/source/fundamentals.txt +++ /dev/null @@ -1,30 +0,0 @@ -============ -Fundamentals -============ - -.. meta:: - :description: Learn how to use the (+driver-long+} to run commands on MongoDB. - -.. toctree:: - :titlesonly: - :maxdepth: 1 - - /fundamentals/connection - /fundamentals/auth - /fundamentals/enterprise-auth - /fundamentals/stable-api - /fundamentals/databases-collections - /fundamentals/data-formats - /fundamentals/crud - /fundamentals/builders - /fundamentals/aggregation - /fundamentals/aggregation-expression-operations - /fundamentals/indexes - /fundamentals/collations - /fundamentals/logging - /fundamentals/monitoring - /fundamentals/gridfs - /fundamentals/encrypt-fields - /fundamentals/time-series - -.. include:: /includes/fundamentals-sections.rst diff --git a/source/fundamentals/crud.txt b/source/fundamentals/crud.txt deleted file mode 100644 index 262ab9d41..000000000 --- a/source/fundamentals/crud.txt +++ /dev/null @@ -1,27 +0,0 @@ -.. _java-crud-operations: - -=============== -CRUD Operations -=============== - -.. default-domain:: mongodb - -.. toctree:: - :caption: CRUD Operations - - /fundamentals/crud/read-operations - /fundamentals/crud/write-operations - /fundamentals/crud/query-document - /fundamentals/crud/compound-operations - -CRUD (Create, Read, Update, Delete) operations enable you to work with -data stored in MongoDB. - -- :doc:`Read Operations ` find and return - documents stored in your database. -- :doc:`Write Operations ` insert, modify, - or delete documents in your database. - -Some operations combine aspects of read and write operations. See our -guide on :doc:`compound operations ` -to learn more about these hybrid methods. diff --git a/source/fundamentals/crud/read-operations.txt b/source/fundamentals/crud/read-operations.txt deleted file mode 100644 index f0c264f90..000000000 --- a/source/fundamentals/crud/read-operations.txt +++ /dev/null @@ -1,29 +0,0 @@ -=============== -Read Operations -=============== - -.. meta:: - :description: Learn about the commands for running read operations on MongoDB by using the {+driver-long+}. - -- :doc:`/fundamentals/crud/read-operations/retrieve` -- :doc:`/fundamentals/crud/read-operations/cursor` -- :doc:`/fundamentals/crud/read-operations/change-streams` -- :doc:`/fundamentals/crud/read-operations/sort` -- :doc:`/fundamentals/crud/read-operations/skip` -- :doc:`/fundamentals/crud/read-operations/limit` -- :doc:`/fundamentals/crud/read-operations/project` -- :doc:`/fundamentals/crud/read-operations/geo` -- :doc:`/fundamentals/crud/read-operations/text` - -.. toctree:: - :caption: Read Operations - - /fundamentals/crud/read-operations/retrieve - /fundamentals/crud/read-operations/cursor - /fundamentals/crud/read-operations/change-streams - /fundamentals/crud/read-operations/sort - /fundamentals/crud/read-operations/skip - /fundamentals/crud/read-operations/limit - /fundamentals/crud/read-operations/project - /fundamentals/crud/read-operations/geo - /fundamentals/crud/read-operations/text diff --git a/source/fundamentals/crud/write-operations.txt b/source/fundamentals/crud/write-operations.txt deleted file mode 100644 index f9ca6ec47..000000000 --- a/source/fundamentals/crud/write-operations.txt +++ /dev/null @@ -1,23 +0,0 @@ -================ -Write Operations -================ - -.. meta:: - :description: Learn about the commands for running MongoDB write operations by using the {+driver-long+}. - -- :doc:`/fundamentals/crud/write-operations/insert` -- :doc:`/fundamentals/crud/write-operations/delete` -- :doc:`/fundamentals/crud/write-operations/modify` -- :doc:`/fundamentals/crud/write-operations/embedded-arrays` -- :doc:`/fundamentals/crud/write-operations/upsert` -- :doc:`/fundamentals/crud/write-operations/bulk` - -.. toctree:: - :caption: Write Operations - - /fundamentals/crud/write-operations/insert - /fundamentals/crud/write-operations/delete - /fundamentals/crud/write-operations/modify - /fundamentals/crud/write-operations/embedded-arrays - /fundamentals/crud/write-operations/upsert - /fundamentals/crud/write-operations/bulk diff --git a/source/fundamentals/data-formats.txt b/source/fundamentals/data-formats.txt deleted file mode 100644 index 280b95ab4..000000000 --- a/source/fundamentals/data-formats.txt +++ /dev/null @@ -1,27 +0,0 @@ -============ -Data Formats -============ - -.. meta:: - :description: Learn how to convert between MongoDB and Java data formats by using the {+driver-long+}. - -- :doc:`/fundamentals/data-formats/document-data-format-bson` -- :doc:`/fundamentals/data-formats/document-data-format-extended-json` -- :doc:`/fundamentals/data-formats/documents` -- :doc:`/fundamentals/data-formats/document-data-format-pojo` -- :doc:`/fundamentals/data-formats/document-data-format-record` -- :doc:`/fundamentals/data-formats/pojo-customization` -- :doc:`/fundamentals/data-formats/codecs` - -.. toctree:: - :caption: Data Formats - - /fundamentals/data-formats/document-data-format-bson - /fundamentals/data-formats/document-data-format-extended-json - /fundamentals/data-formats/documents - /fundamentals/data-formats/document-data-format-pojo - /fundamentals/data-formats/document-data-format-record - /fundamentals/data-formats/pojo-customization - /fundamentals/data-formats/codecs - - diff --git a/source/fundamentals/encrypt-fields.txt b/source/fundamentals/encrypt-fields.txt deleted file mode 100644 index fe8226bac..000000000 --- a/source/fundamentals/encrypt-fields.txt +++ /dev/null @@ -1,3 +0,0 @@ -.. _java-fle: - -.. sharedinclude:: dbx/encrypt-fields.rst diff --git a/source/quick-start.txt b/source/get-started.txt similarity index 87% rename from source/quick-start.txt rename to source/get-started.txt index d63082b69..3b2f5feb4 100644 --- a/source/quick-start.txt +++ b/source/get-started.txt @@ -1,8 +1,8 @@ .. _java-sync-quickstart: -======================= -Java Driver Quick Start -======================= +================================ +Get Started with the Java Driver +================================ .. facet:: :name: genre @@ -17,6 +17,12 @@ Java Driver Quick Start :depth: 2 :class: singlecol +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Quick Reference + Introduction ------------ @@ -52,7 +58,7 @@ If you are using `Gradle `__, add the following to your .. note:: - We recommend that you use a build tool to install the + We recommend that you use a build tool, such as Maven or Gradle, to install the {+driver-short+}. However, if you must download the driver and dependencies, you can find the JAR files in the `MongoDB Group Maven repository `__. @@ -113,7 +119,7 @@ Create a new file ``QuickStartPojoExample.java`` in the same package directory as your ``Movie`` file in your project. Use the following sample code to run a query on your sample dataset in MongoDB Atlas, replacing the value of the ``uri`` variable with your MongoDB Atlas connection string. -Ensure you replace the "" section of the connection string with +Ensure you replace the "" section of the connection string with the password you created for your user that has **atlasAdmin** permissions: .. literalinclude:: /includes/quick-start/code-snippets/QuickStartPojoExample.java @@ -127,8 +133,8 @@ the password you created for your user that has **atlasAdmin** permissions: See the following links For more information about using POJOs to store and retrieve data: -- :doc:`Guide on using POJOs to store and retrieve data` -- :doc:`Guide on custom serialization of POJOs ` +- :doc:`Guide on using POJOs to store and retrieve data` +- :doc:`Guide on custom serialization of POJOs ` Next steps ---------- diff --git a/source/quick-reference.txt b/source/get-started/quick-reference.txt similarity index 100% rename from source/quick-reference.txt rename to source/get-started/quick-reference.txt diff --git a/source/includes/faq/code-snippets/FaqExample.java b/source/includes/faq/code-snippets/FaqExample.java index 7bc730d7a..ba355e8bc 100644 --- a/source/includes/faq/code-snippets/FaqExample.java +++ b/source/includes/faq/code-snippets/FaqExample.java @@ -34,7 +34,7 @@ public static void main(String[] args) { fromProviders(pojoCodecProvider)); // end myDateAsStringCodec - String uri = "mongodb+srv://:@?retryWrites=true&w=majority"; + String uri = "mongodb+srv://:@?retryWrites=true&w=majority"; try (MongoClient mongoClient = MongoClients.create(uri)) { diff --git a/source/includes/fundamentals/code-snippets/LongRepresentableCodec.java b/source/includes/fundamentals/code-snippets/LongRepresentableCodec.java new file mode 100644 index 000000000..51bc2cea9 --- /dev/null +++ b/source/includes/fundamentals/code-snippets/LongRepresentableCodec.java @@ -0,0 +1,77 @@ +package fundamentals; + +import org.bson.BsonInvalidOperationException; +import org.bson.BsonReader; +import org.bson.BsonType; +import org.bson.BsonWriter; +import org.bson.codecs.Codec; +import org.bson.codecs.DecoderContext; +import org.bson.codecs.EncoderContext; +import org.bson.codecs.RepresentationConfigurable; +import org.bson.codecs.configuration.CodecConfigurationException; + + +// start class +public class LongRepresentableCodec implements Codec, RepresentationConfigurable { + private final BsonType representation; + + /** + * Constructs a LongRepresentableCodec with a Int64 representation. + */ + public LongRepresentableCodec() { + representation = BsonType.INT64; + } + + private LongRepresentableCodec(final BsonType representation) { + this.representation = representation; + } + + @Override + public BsonType getRepresentation() { + return representation; + } + + @Override + public Codec withRepresentation(final BsonType representation) { + if (representation != BsonType.INT64 && representation != BsonType.DATE_TIME) { + throw new CodecConfigurationException(representation + + " is not a supported representation for LongRepresentableCodec"); + } + return new LongRepresentableCodec(representation); + } + + + @Override + public void encode(final BsonWriter writer, final Long value, final EncoderContext encoderContext) { + switch (representation) { + case INT64: + writer.writeInt64(value); + break; + case DATE_TIME: + writer.writeDateTime(value); + break; + default: + throw new BsonInvalidOperationException("Cannot encode a Long to a " + + representation); + } + } + + @Override + public Long decode(final BsonReader reader, final DecoderContext decoderContext) { + switch (representation) { + case INT64: + return reader.readInt64(); + case DATE_TIME: + return reader.readDateTime(); + default: + throw new CodecConfigurationException("Cannot decode " + representation + + " to a Long"); + } + } + + @Override + public Class getEncoderClass() { + return Long.class; + } +} +// end class \ No newline at end of file diff --git a/source/includes/fundamentals/code-snippets/Transaction.java b/source/includes/fundamentals/code-snippets/Transaction.java new file mode 100644 index 000000000..1756b41dd --- /dev/null +++ b/source/includes/fundamentals/code-snippets/Transaction.java @@ -0,0 +1,42 @@ +package fundamentals; + +// begin imports +import com.mongodb.client.*; +import com.mongodb.client.MongoClient; +import com.mongodb.client.model.WriteConcern; +import org.bson.Document; + +import java.util.Arrays; +// end imports + +public class Transaction { + public static void main(String[] args) { + // start transaction + String connectionString = ""; // Replace with your connection string + try (MongoClient mongoClient = MongoClients.create(connectionString)) { + MongoDatabase database = mongoClient.getDatabase("transaction_db"); + MongoCollection collection = database.getCollection("books"); + + // Sets transaction options + TransactionOptions txnOptions = TransactionOptions.builder() + .writeConcern(WriteConcern.MAJORITY) + .build(); + + try (ClientSession session = mongoClient.startSession()) { + + // Uses withTransaction and lambda for transaction operations + session.withTransaction(() -> { + collection.insertMany(session, Arrays.asList( + new Document("title", "The Bluest Eye").append("author", "Toni Morrison"), + new Document("title", "Sula").append("author", "Toni Morrison"), + new Document("title", "Song of Solomon").append("author", "Toni Morrison") + )); + return null; // Return value as expected by the lambda + }, txnOptions); + } + } catch (Exception e) { + e.printStackTrace(); + } + // end transaction + } +} diff --git a/source/includes/fundamentals/code-snippets/auth-credentials-default.rst b/source/includes/fundamentals/code-snippets/auth-credentials-default.rst index c60212ccd..391bd9153 100644 --- a/source/includes/fundamentals/code-snippets/auth-credentials-default.rst +++ b/source/includes/fundamentals/code-snippets/auth-credentials-default.rst @@ -1,6 +1,6 @@ .. code-block:: java - MongoCredential credential = MongoCredential.createCredential("", "", ""); + MongoCredential credential = MongoCredential.createCredential("", "", ""); MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() diff --git a/source/includes/fundamentals/code-snippets/auth-credentials-gssapi-properties.rst b/source/includes/fundamentals/code-snippets/auth-credentials-gssapi-properties.rst index 44be88a73..44fa2e0de 100644 --- a/source/includes/fundamentals/code-snippets/auth-credentials-gssapi-properties.rst +++ b/source/includes/fundamentals/code-snippets/auth-credentials-gssapi-properties.rst @@ -1,5 +1,5 @@ .. code-block:: java - MongoCredential credential = MongoCredential.createGSSAPICredential(); + MongoCredential credential = MongoCredential.createGSSAPICredential(); credential = credential.withMechanismProperty(MongoCredential.SERVICE_NAME_KEY, "myService"); diff --git a/source/includes/fundamentals/code-snippets/auth-credentials-gssapi-subject-key.rst b/source/includes/fundamentals/code-snippets/auth-credentials-gssapi-subject-key.rst index 69af1abc0..bb8dac028 100644 --- a/source/includes/fundamentals/code-snippets/auth-credentials-gssapi-subject-key.rst +++ b/source/includes/fundamentals/code-snippets/auth-credentials-gssapi-subject-key.rst @@ -4,6 +4,6 @@ loginContext.login(); Subject subject = loginContext.getSubject(); - MongoCredential credential = MongoCredential.createGSSAPICredential(); + MongoCredential credential = MongoCredential.createGSSAPICredential(); credential = credential.withMechanismProperty(MongoCredential.JAVA_SUBJECT_KEY, subject); diff --git a/source/includes/fundamentals/code-snippets/auth-credentials-gssapi-ticket-cache.rst b/source/includes/fundamentals/code-snippets/auth-credentials-gssapi-ticket-cache.rst index 2994dee8b..7070930ed 100644 --- a/source/includes/fundamentals/code-snippets/auth-credentials-gssapi-ticket-cache.rst +++ b/source/includes/fundamentals/code-snippets/auth-credentials-gssapi-ticket-cache.rst @@ -3,7 +3,7 @@ /* all MongoClient instances sharing this instance of KerberosSubjectProvider will share a Kerberos ticket cache */ String myLoginContext = "myContext"; - MongoCredential credential = MongoCredential.createGSSAPICredential(); + MongoCredential credential = MongoCredential.createGSSAPICredential(); /* login context defaults to "com.sun.security.jgss.krb5.initiate" if unspecified in KerberosSubjectProvider */ credential = credential.withMechanismProperty(MongoCredential.JAVA_SUBJECT_PROVIDER_KEY, diff --git a/source/includes/fundamentals/code-snippets/auth-credentials-gssapi.rst b/source/includes/fundamentals/code-snippets/auth-credentials-gssapi.rst index 9a78d0853..0cb0795f9 100644 --- a/source/includes/fundamentals/code-snippets/auth-credentials-gssapi.rst +++ b/source/includes/fundamentals/code-snippets/auth-credentials-gssapi.rst @@ -1,6 +1,6 @@ .. code-block:: java - MongoCredential credential = MongoCredential.createGSSAPICredential(); + MongoCredential credential = MongoCredential.createGSSAPICredential(); MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() diff --git a/source/includes/fundamentals/code-snippets/auth-credentials-ldap.rst b/source/includes/fundamentals/code-snippets/auth-credentials-ldap.rst index 305e3201c..a2b19de44 100644 --- a/source/includes/fundamentals/code-snippets/auth-credentials-ldap.rst +++ b/source/includes/fundamentals/code-snippets/auth-credentials-ldap.rst @@ -1,6 +1,6 @@ .. code-block:: java - MongoCredential credential = MongoCredential.createPlainCredential(, "$external", ); + MongoCredential credential = MongoCredential.createPlainCredential(, "$external", ); MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() diff --git a/source/includes/fundamentals/code-snippets/auth-credentials-sha1.rst b/source/includes/fundamentals/code-snippets/auth-credentials-sha1.rst index 29644d77c..c2f382a93 100644 --- a/source/includes/fundamentals/code-snippets/auth-credentials-sha1.rst +++ b/source/includes/fundamentals/code-snippets/auth-credentials-sha1.rst @@ -1,6 +1,6 @@ .. code-block:: java - MongoCredential credential = MongoCredential.createScramSha1Credential("", "", ""); + MongoCredential credential = MongoCredential.createScramSha1Credential("", "", ""); MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() diff --git a/source/includes/fundamentals/code-snippets/auth-credentials-sha256.rst b/source/includes/fundamentals/code-snippets/auth-credentials-sha256.rst index 2d16a3aa5..02af4fddb 100644 --- a/source/includes/fundamentals/code-snippets/auth-credentials-sha256.rst +++ b/source/includes/fundamentals/code-snippets/auth-credentials-sha256.rst @@ -1,6 +1,6 @@ .. code-block:: java - MongoCredential credential = MongoCredential.createScramSha256Credential("", "", ""); + MongoCredential credential = MongoCredential.createScramSha256Credential("", "", ""); MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() diff --git a/source/includes/fundamentals/code-snippets/crypt-gradle-versioned.rst b/source/includes/fundamentals/code-snippets/crypt-gradle-versioned.rst new file mode 100644 index 000000000..2bb77055b --- /dev/null +++ b/source/includes/fundamentals/code-snippets/crypt-gradle-versioned.rst @@ -0,0 +1,5 @@ +.. code-block:: groovy + + dependencies { + implementation 'org.mongodb:mongodb-crypt:{+mongocrypt-version+}' + } \ No newline at end of file diff --git a/source/includes/fundamentals/code-snippets/crypt-maven-versioned.rst b/source/includes/fundamentals/code-snippets/crypt-maven-versioned.rst new file mode 100644 index 000000000..0b2c3b0e4 --- /dev/null +++ b/source/includes/fundamentals/code-snippets/crypt-maven-versioned.rst @@ -0,0 +1,9 @@ +.. code-block:: xml + + + + org.mongodb + mongodb-crypt + {+mongocrypt-version+} + + diff --git a/source/includes/fundamentals/code-snippets/wildfly-module-with-version.rst b/source/includes/fundamentals/code-snippets/wildfly-module-with-version.rst new file mode 100644 index 000000000..1a86ee8fb --- /dev/null +++ b/source/includes/fundamentals/code-snippets/wildfly-module-with-version.rst @@ -0,0 +1,16 @@ +.. code-block:: xml + :caption: module.xml + + + + + + + + + + + + + + \ No newline at end of file diff --git a/source/includes/fundamentals/code-snippets/wildfly-module-with-version.xml b/source/includes/fundamentals/code-snippets/wildfly-module-with-version.xml deleted file mode 100644 index b1fd9e6b5..000000000 --- a/source/includes/fundamentals/code-snippets/wildfly-module-with-version.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/source/includes/quick-reference/QuickReferenceSnippets.java b/source/includes/quick-reference/QuickReferenceSnippets.java index d58dad57a..90a0c0a98 100644 --- a/source/includes/quick-reference/QuickReferenceSnippets.java +++ b/source/includes/quick-reference/QuickReferenceSnippets.java @@ -171,7 +171,7 @@ private static void searchTextExample(MongoCollection coll) { public static void main(String[] args) { // Replace the uri string with your MongoDB deployment's connection string - String uri = "mongodb+srv://:@?retryWrites=true&w=majority"; + String uri = "mongodb+srv://:@?retryWrites=true&w=majority"; try (MongoClient mongoClient = MongoClients.create(uri)) { MongoDatabase database = mongoClient.getDatabase("movies"); diff --git a/source/index.txt b/source/index.txt index 4b535c1ce..40cf54f55 100644 --- a/source/index.txt +++ b/source/index.txt @@ -18,20 +18,23 @@ MongoDB Java Driver :titlesonly: :maxdepth: 1 - Quick Start - /quick-reference - /whats-new - /usage-examples - /fundamentals - /api-documentation - /faq - /connection-troubleshooting - /issues-and-help - /integrations - /compatibility - /upgrade - /legacy - View the Source + Get Started + Connect + CRUD Operations + Databases & Collections + Aggregation + Builders + Data Formats + Indexes + Run a Command + Atlas Search + Atlas Vector Search + Logging & Monitoring + Security + Third-Party Integrations + Reference + API Documentation + Issues & Help Introduction ------------ @@ -66,11 +69,11 @@ Quick Reference See driver syntax examples for common MongoDB commands in the :ref:`Quick Reference ` section. -What's New ----------- +Release Notes +------------- For a list of new features and changes in each version, see the -:ref:`What's New ` section. +:ref:`Release Notes ` section. Usage Examples -------------- @@ -114,13 +117,6 @@ and links to the API documentation. * - `Legacy Java Driver <{+api+}/apidocs/mongodb-driver-legacy/index.html>`__ - Legacy API -FAQ ---- - -For answers to commonly asked questions about the MongoDB -Java Driver, see the :doc:`Frequently Asked Questions (FAQ) ` -section. - Connection Troubleshooting -------------------------- @@ -155,6 +151,12 @@ Learn what changes you might need to make to your application to upgrade driver versions in the :ref:`Upgrade Driver Versions ` section. +Validate Driver Artifact Signatures +----------------------------------- + +Learn about how to validate signatures of {+driver-short+} artifacts +published on Maven in the :ref:`Validate Driver Artifact Signatures ` section. + Migrate from the Legacy API --------------------------- @@ -162,7 +164,6 @@ Learn what changes you might need to make to your application to migrate from the legacy API to the current API in the :ref:`Migrate from the Legacy API ` section. - Learn ------ diff --git a/source/fundamentals/indexes.txt b/source/indexes.txt similarity index 99% rename from source/fundamentals/indexes.txt rename to source/indexes.txt index f05be7497..bce5ff2e5 100644 --- a/source/fundamentals/indexes.txt +++ b/source/indexes.txt @@ -595,4 +595,4 @@ For prior versions of MongoDB, pass "*" as a parameter to your call to For more information about the methods in this section, see the following API Documentation: - `dropIndex() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#dropIndex(java.lang.String)>`__ -- `dropIndexes() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#dropIndexes()>`__ +- `dropIndexes() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#dropIndexes()>`__ \ No newline at end of file diff --git a/source/integrations.txt b/source/integrations.txt index d8929a1ca..fa329cc8a 100644 --- a/source/integrations.txt +++ b/source/integrations.txt @@ -1,8 +1,8 @@ .. _java-integrations: -=================== -Driver Integrations -=================== +======================== +Third-Party Integrations +======================== .. facet:: :name: genre diff --git a/source/issues-and-help.txt b/source/issues-and-help.txt index 99e734008..e2a8e327b 100644 --- a/source/issues-and-help.txt +++ b/source/issues-and-help.txt @@ -4,7 +4,12 @@ Issues & Help ============= -.. default-domain:: mongodb +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: java sync, troubleshooting, feedback .. contents:: On this page :local: @@ -13,28 +18,37 @@ Issues & Help :class: singlecol We are lucky to have a vibrant MongoDB Java community that includes users -with varying levels of experience using the Java driver. We find the quickest -way to get support for general questions is through the `MongoDB Community Forums `_. - -Refer to our `support channels `_ -documentation for more information. +with varying levels of experience using the {+driver-short+}. The +quickest way to get support for general questions is through the +:community-forum:`MongoDB Community Forums `. Bugs / Feature Requests ----------------------- -If you think you've found a bug or want to see a new feature in the Java -driver, please open a case in our issue management tool, JIRA: +If you have feedback about the {+driver-short+}, visit the `MongoDB +Feedback Engine `__ and select +:guilabel:`Drivers` from the list of products on the right side of +your screen. You can propose improvements, report issues, and provide +other types of feedback by using this site. + +You can also open a case in Jira, our issue management tool, to identify +bugs or propose improvements. The following steps describe how to create +a Jira issue: -* `Create an account and login `_. -* Navigate to `the JAVA project `_. -* Click :guilabel:`Create`. Please provide as much information as possible - about the issue and the steps to reproduce it. +1. Visit the `MongoDB Jira issue tracker `__ and click the + `signup link. `__ + Create an account, and then log in to Jira. +#. Navigate to the `JAVA Jira project. `__ +#. Click :guilabel:`Create` to create a ticket. Please provide as much + information as possible about the issue or request in the ticket. -Bug reports in JIRA for the Java driver and the Core Server (SERVER) project are **public**. +.. note:: -If you’ve identified a security vulnerability in a driver or any other -MongoDB project, please report it according to the instructions found in the -:manual:`Create a Vulnerability Report page `. + Bug reports in the JAVA Jira project are publicly viewable. + +If you’ve identified a security vulnerability in any official MongoDB +product, please report it according to the instructions found in the +:manual:`Create a Vulnerability Report page. ` Pull Requests ------------- @@ -57,4 +71,3 @@ Finally, ensure that the code passes gradle checks. .. code-block:: bash $ ./gradlew check - diff --git a/source/logging-monitoring.txt b/source/logging-monitoring.txt new file mode 100644 index 000000000..af9de0f1b --- /dev/null +++ b/source/logging-monitoring.txt @@ -0,0 +1,14 @@ +====================== +Logging and Monitoring +====================== + +.. meta:: + :description: Learn how to use the {+driver-long+} logging and monitoring tools. + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Logging + Monitoring + Change Streams \ No newline at end of file diff --git a/source/fundamentals/crud/read-operations/change-streams.txt b/source/logging-monitoring/change-streams.txt similarity index 100% rename from source/fundamentals/crud/read-operations/change-streams.txt rename to source/logging-monitoring/change-streams.txt diff --git a/source/fundamentals/logging.txt b/source/logging-monitoring/logging.txt similarity index 99% rename from source/fundamentals/logging.txt rename to source/logging-monitoring/logging.txt index 3b11c9bc4..d7dc66097 100644 --- a/source/fundamentals/logging.txt +++ b/source/logging-monitoring/logging.txt @@ -38,7 +38,7 @@ You will learn how to: This guide shows how to record events in the driver. If you would like to learn how to use information about the activity of the driver in code, consider reading our -:doc:`guide on monitoring `. +:doc:`guide on monitoring `. Set Up a Logger --------------- diff --git a/source/fundamentals/monitoring.txt b/source/logging-monitoring/monitoring.txt similarity index 97% rename from source/fundamentals/monitoring.txt rename to source/logging-monitoring/monitoring.txt index 8c2fdecbc..2d784bbbd 100644 --- a/source/fundamentals/monitoring.txt +++ b/source/logging-monitoring/monitoring.txt @@ -37,7 +37,7 @@ In this guide you will learn how to perform these tasks: This guide shows how to use information about the activity of the driver in code. If you would like to learn how to record events in the driver, -consider reading our :doc:`guide on logging `. +consider reading our :doc:`guide on logging `. .. _monitoring-monitor-events: @@ -162,7 +162,7 @@ The driver defines nine SDAM events. The driver divides these nine events between three separate listener interfaces which each listen for three of the nine events. Here are the three interfaces and the events they listen for: -- ``ClusterListener``: :spec:`topology ` +- ``ClusterListener``: :spec:`topology ` related events - ``ServerListener``: events related to ``mongod`` or ``mongos`` processes - ``ServerMonitorListener``: heartbeat related events @@ -172,7 +172,11 @@ implements one of the three preceding interfaces and register an instance of tha class with your ``MongoClient`` instance. For a detailed description of each SDAM event in the driver, see the -:spec:`MongoDB SDAM Logging and Monitoring Specification `. +:spec:`MongoDB SDAM Logging and Monitoring Specification `. + +.. note:: Load Balanced Mode + + The driver doesn't emit heartbeat related events when in load balanced mode. For more details about SDAM events with load balancing, see :spec:`MongoDB Load Balancer Support Specification `. Example ^^^^^^^ diff --git a/source/reference.txt b/source/reference.txt new file mode 100644 index 000000000..6bdb9fd27 --- /dev/null +++ b/source/reference.txt @@ -0,0 +1,20 @@ +========= +Reference +========= + +.. meta:: + :description: Learn about versioning in the {+driver-long+}. + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Release Notes + Compatibility + Upgrade + Migrate from the Legacy API + +- :ref:`Release Notes ` +- :ref:`Compatibility ` +- :ref:`Upgrade ` +- :ref:`Migrate from the Legacy API ` diff --git a/source/compatibility.txt b/source/reference/compatibility.txt similarity index 92% rename from source/compatibility.txt rename to source/reference/compatibility.txt index 7295fb21e..5007723ea 100644 --- a/source/compatibility.txt +++ b/source/reference/compatibility.txt @@ -42,7 +42,7 @@ The first column lists the driver version. .. sharedinclude:: dbx/compatibility-table-legend.rst -.. include:: /includes/mongodb-compatibility-table-java.rst +.. sharedinclude:: dbx/mongodb-compatibility-table-java.rst Language Compatibility ---------------------- @@ -54,7 +54,7 @@ Java versions. The first column lists the driver version. -.. include:: /includes/language-compatibility-table-java.rst +.. sharedinclude:: dbx/language-compatibility-table-java.rst For more information about how to read the compatibility tables, see our guide on :ref:`MongoDB Compatibility Tables. ` diff --git a/source/legacy.txt b/source/reference/legacy.txt similarity index 99% rename from source/legacy.txt rename to source/reference/legacy.txt index d46411db7..3a0d88d1b 100644 --- a/source/legacy.txt +++ b/source/reference/legacy.txt @@ -62,7 +62,7 @@ API include: - **Native POJO support**, which provides automatic or custom mapping between MongoDB documents and Java objects -To learn about more features of the current API, see :ref:`java-whats-new`. +To learn about more features of the current API, see :ref:`java-release-notes`. API Changes diff --git a/source/reference/release-notes.txt b/source/reference/release-notes.txt new file mode 100644 index 000000000..ef7fc4257 --- /dev/null +++ b/source/reference/release-notes.txt @@ -0,0 +1,389 @@ +.. _java-whats-new: +.. _java-release-notes: + +============= +Release Notes +============= + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: java sync, backwards compatibility, update, version + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Learn what's new in: + +* :ref:`Version 5.1.3 ` +* :ref:`Version 5.1.2 ` +* :ref:`Version 5.1.1 ` +* :ref:`Version 5.1 ` +* :ref:`Version 5.0 ` +* :ref:`Version 4.11 ` +* :ref:`Version 4.10 ` + +.. _java-version-5.1.3: + +What's New in 5.1.3 +------------------- + +The 5.1.3 driver patch release includes the following changes: + +.. sharedinclude:: dbx/jvm/v5.1.3-wn-items.rst + +.. _java-version-5.1.2: + +What's New in 5.1.2 +------------------- + +The 5.1.2 driver patch release includes the following changes: + +- Fixes an issue that prevents the driver from encoding and + decoding concrete classes that extend generic base classes, in cases that you + specify the base class as the generic type of the ``MongoCollection`` instance. + +- Fixes an issue related to how domain names are validated when you use + SOCKS5 proxy functionality, allowing you to use domain names with more than + six characters in the top-level domain. + +.. _java-version-5.1.1: + +What's New in 5.1.1 +------------------- + +The 5.1.1 driver patch release includes the following changes: + +- When using the ``MONGODB-OIDC`` authentication mechanism, you must not + include comma characters in the ``authMechanismProperties`` connection + string value. To learn more about this behavior, see the + :ref:`MONGODB-OIDC ` section of the Enterprise + Authentication guide. + +- Optimizes GridFS throughput by removing redundant byte array cloning. + The ``GridFSDownloadStream`` and ``GridFSUploadStream`` types use + the ``BsonDocument`` type instead of ``Document``. + +.. _version-5.1: + +What's New in 5.1 +----------------- + +.. warning:: Deprecations in this release + + To avoid breaking changes in future major releases of the driver, + replace any application code that depends on deprecated program elements. + +This section includes the following information: + +- :ref:`java-deprecations-5.1` +- :ref:`java-improvements-5.1` +- :ref:`java-new-features-5.1` + +.. _java-deprecations-5.1: + +Deprecations in 5.1 +~~~~~~~~~~~~~~~~~~~ + +- Support for {+mdb-server+} v3.6 is deprecated and will be removed in the + next driver version release. To learn how to upgrade your {+mdb-server+} + deployment, see :manual:`Release Notes ` in the {+mdb-server+} + manual. + +.. _java-improvements-5.1: + +Improvements in 5.1 +~~~~~~~~~~~~~~~~~~~ + +- Internal testing of GraalVM native image technology. These tests involve building + native applications by using the GraalVM native-image tool. +- Enhanced support for the MONGODB-OIDC authentication mechanism. For more information about + OIDC, see the :ref:`mongodb-oidc` section of the Enterprise Authentication Mechanisms guide. + +.. _java-new-features-5.1: + +New Features in 5.1 +~~~~~~~~~~~~~~~~~~~ + +- Introduces the ``serverMonitoringMode`` connection URI option. For more information about + this option, see the :ref:`connection-options` guide. + +.. _version-5.0: + +What's New in 5.0 +----------------- + +.. warning:: Breaking changes in this release + + This driver version introduces breaking changes. For a list of these changes, see + the :ref:`Version 5.0 Breaking Changes section ` in the + Upgrade guide. + +.. warning:: Deprecations in this release + + To avoid breaking changes in future major releases of the driver, + replace any application code that depends on deprecated program elements. + +This section includes the following information: + +- :ref:`java-deprecations-5.0` +- :ref:`java-behavioral-changes-5.0` +- :ref:`java-new-features-5.0` + +.. _java-deprecations-5.0: + +Deprecations in 5.0 +~~~~~~~~~~~~~~~~~~~ + +- The ``org.mongodb.scala.Observable.completeWithUnit()`` method is deprecated. + This method is not useful anymore because + the driver now exposes ``org.mongodb.scala.Observable[Unit]`` + instead of ``org.mongodb.scala.Observable[Void]``. + This relates to a :ref:`breaking change about Observables in this release + `. + +.. _java-behavioral-changes-5.0: + +Behavioral changes in 5.0 +~~~~~~~~~~~~~~~~~~~~~~~~~ + +- The ``getElapsedTime()`` method on ``com.mongodb.event.ConnectionReadyEvent`` + includes the time taken to deliver the ``ConnectionCreatedEvent``. That is, + the time returned includes the duration of the + ``com.mongodb.event.ConnectionPoolListener.connectionCreated()`` method. + + The ``getElapsedTime()`` methods on + ``com.mongodb.event.ConnectionCheckedOutFailedEvent`` and + ``com.mongodb.event.ConnectionCheckedOutEvent`` include the time taken to + deliver the ``com.mongodb.event.ConnectionCheckOutStartedEvent``. That is, the + time returned includes the duration of the + ``com.mongodb.eventConnectionPoolListener.connectionCheckOutStarted()`` method. + +.. _java-new-features-5.0: + +New features in 5.0 +~~~~~~~~~~~~~~~~~~~ + +The 5.0 driver release introduces the following features: + +- Adds support for the ``authorizedCollection`` option of + the ``listCollections`` command. This was done by changing the + ``com.mongodb.client.MongoDatabase.listCollectionNames()`` methods. + The return type is now ``com.mongodb.client.ListCollectionNamesIterable``, + while previously it was a ``MongoIterable``. + This change allows the return value to be + configured using the ``ListCollectionNamesIterable.authorizedCollections()`` + method and specifying the ``authorizedCollections`` option. Equivalent changes + were made to following classes and interfaces: + + - ``com.mongodb.reactivestreams.client.MongoDatabase`` + - ``org.mongodb.scala.MongoDatabase`` + - ``com.mongodb.kotlin.client.MongoDatabase`` + - ``com.mongodb.kotlin.client.coroutine.MongoDatabase`` + + These changes introduce a :ref:`binary breaking change to the listCollectionsNames() + method `. For more information + about the ``MongoDatabase.listCollectionNames()`` method and the + ``authorizedCollections`` option, see the + :manual:`listCollections ` Server manual + page or :ref:`java-collection-names`. + +.. note:: + + The v5.0.2 patch release fixed an issue related to how domain names are validated when you use + SOCKS5 proxy functionality, allowing you to use domain names with more than + six characters in the top-level domain. + +.. _version-4.11: + +What's New in 4.11 +------------------ + +This section includes the following information: + +- :ref:`java-deprecations-4.11` +- :ref:`java-new-features-4.11` + +.. _java-deprecations-4.11: + +Deprecations in 4.11 +~~~~~~~~~~~~~~~~~~~~ + +.. warning:: Deprecations in this release + + To avoid breaking changes in future major releases of the driver, + replace any application code that depends on deprecated methods and types. + +The 4.11 driver release deprecates the following items: + +- The ``getStats()`` and ``isCapped()`` instance methods of the + ``DBCollection`` class are deprecated. The corresponding server + commands are deprecated in MongoDB v6.2 and later. Use the ``$collStats`` + aggregation pipeline stage to retrieve the information provided by these + methods instead. You can run the aggregation as shown in the following code + example: + + .. code-block:: java + + Cursor cursor = collection.aggregate(Arrays.asList( + new BasicDBObject("$collStats", + new BasicDBObject("storageStats", new BasicDBObject()))), + AggregationOptions.builder().build() + ); + + To determine whether a collection is a capped collection, access the value + of the ``storageStats.capped`` field returned by ``Cursor`` instance in the + preceding example aggregation. + + To learn more about the ``$collStats`` aggregation operator, see the + :manual:`$collStats (aggregation) ` + Server manual entry. + +- The following network address-related methods are deprecated and will be removed + in v5.0: + + - The `ServerAddress <{+api+}/apidocs/mongodb-driver-core/com/mongodb/ServerAddress.html>`__ + methods ``getSocketAddress()`` and ``getSocketAddresses()``. + + Instead of ``getSocketAddress()``, use the ``getByName()`` instance + method of ``java.net.InetAddress``. + + Instead of ``getSocketAddresses()``, use the ``getAllByName()`` instance + method of ``java.net.InetAddress``. + + - The `UnixServerAddress <{+api+}/apidocs/mongodb-driver-core/com/mongodb/UnixServerAddress.html>`__ + method ``getUnixSocketAddress()``. + + Instead of ``getUnixSocketAddress()``, construct an instance of + ``jnr.unixsocket.UnixSocketAddress``. Pass the full path of the UNIX + socket file to the constructor. By default, MongoDB creates a UNIX + socket file located at ``"/tmp/mongodb-27017.sock"``. To learn more + about the ``UnixSocketAddress``, see the `UnixSocketAddress `__ API documentation. + +- The following methods and types related to the + `StreamFactory `__ + interface are deprecated and scheduled for removal in v5.0: + + - ``streamFactoryFactory()`` method from ``MongoClientSettings.Builder`` + - ``getStreamFactoryFactory()`` method from ``MongoClientSettings`` + - ``NettyStreamFactoryFactory`` class + - ``NettyStreamFactory`` class + - ``AsynchronousSocketChannelStreamFactory`` class + - ``AsynchronousSocketChannelStreamFactoryFactory`` class + - ``BufferProvider`` class + - ``SocketStreamFactory`` class + - ``Stream`` class + - ``StreamFactory`` class + - ``StreamFactoryFactory`` class + - ``TlsChannelStreamFactoryFactory`` class + + If you configure Netty by using + ``MongoClientSettings.Builder.streamFactoryFactory()``, your code might resemble + the following: + + .. code-block:: java + :emphasize-lines: 6 + :copyable: false + + import com.mongodb.connection.netty.NettyStreamFactoryFactory; + + // ... + + MongoClientSettings settings = MongoClientSettings.builder() + .streamFactoryFactory(NettyStreamFactoryFactory.builder().build()) + .build(); + + Replace this code with the `TransportSettings.nettyBuilder() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/connection/TransportSettings.html>`__ + as shown in the following example: + + .. code-block:: java + :emphasize-lines: 6 + + import com.mongodb.connection.TransportSettings; + + // ... + + MongoClientSettings settings = MongoClientSettings.builder() + .transportSettings(TransportSettings.nettyBuilder().build()) + .build(); + +.. _java-new-features-4.11: + +New Features in 4.11 +~~~~~~~~~~~~~~~~~~~~ + +New features of the 4.11 driver release include: + +- Support for connecting to MongoDB by using a SOCKS5 proxy. To learn more + see :ref:`java-connect-socks`. + +.. note:: + + The v4.11.3 patch release fixed an issue related to how domain names are validated when you use + SOCKS5 proxy functionality, allowing you to use domain names with more than + six characters in the top-level domain. + +- Added the ``getSplitEvent()`` method to the ``ChangeStreamDocument`` class + to identify fragments of a change stream event that exceeds 16MB. You must + use the aggregation stage ``$changeStreamSplitLargeEvent`` in your change + stream to handle events that exceed 16MB. To learn more, see :ref:`java-split-change-stream-events`. + +- Added an aggregation stage builder for ``$vectorSearch``. To learn more, see :ref:`Atlas Vector Search `. + +- Added Atlas Search index management helpers. To learn more, see :ref:`Atlas Search Indexes `. + +- Updated Snappy and Zstd compression library dependency versions. To learn + more about the current dependency versions, see :ref:`network-compression`. +- Added ``getElapsedTime()`` methods to the following classes to monitor the + duration of connection pool events: + + - `ConnectionCheckOutFailedEvent <{+api+}/apidocs/mongodb-driver-core/com/mongodb/event/ConnectionCheckOutFailedEvent.html>`__ + - `ConnectionCheckedOutEvent <{+api+}/apidocs/mongodb-driver-core/com/mongodb/event/ConnectionCheckedOutEvent.html>`__ + - `ConnectionReadyEvent <{+api+}/apidocs/mongodb-driver-core/com/mongodb/event/ConnectionReadyEvent.html>`__ + +- Support for Java 21 virtual threads and structured concurrency. The driver + internals were updated to avoid unnecessary pinning of virtual threads + and to preserve interrupted status of a thread, as the latter matters for + structured concurrency where it is used for cancellation. + + To learn more about virtual threads, see the `Virtual Threads `__ + JDK enhancement proposal. To learn more about structured concurrency, see the + `Structured Concurrency `__ + JDK enhancement proposal. + +- Updated API documentation for the following types: + + - `ClusterListener <{+api+}/apidocs/mongodb-driver-core/com/mongodb/event/ClusterListener.html>`__ + - `ServerListener <{+api+}/apidocs/mongodb-driver-core/com/mongodb/event/ServerListener.html>`__ + - `ServerMonitorListener <{+api+}/apidocs/mongodb-driver-core/com/mongodb/event/ServerMonitorListener.html>`__ + +.. _version-4.10: + +What's New in 4.10 +------------------ + +New features of the 4.10 driver release include: + +- Implementation of the ``Accumulators.percentile()`` and + ``Accumulators.median()`` methods for statistical aggregations. +- Interfaces in the ``com.mongodb.client.model.search`` package are now + marked as ``@Sealed`` instead of ``@Evolving``. Sealed interfaces must + not be extended or implemented by consumers of the library. +- Resolved an issue where the driver emitted duplicate log messages for + retry operations. The driver now correctly emits one log message for + each retry operation. +- The ``org.bson.codecs.Parameterizable`` interface is deprecated. Instead of + implementing this interface on a custom ``Codec`` type, + override the ``CodecProvider.get()`` method on the + codec's ``CodecProvider`` if the codec is intended for a parameterized + type. +- Support for custom DNS resolvers. +- Support for :ref:`qe-manual-feature-qe` (QE). To learn + more about the requirements for using the QE feature, see the + :ref:`Queryable Encryption Driver Compatibility Table + `. \ No newline at end of file diff --git a/source/upgrade.txt b/source/reference/upgrade.txt similarity index 98% rename from source/upgrade.txt rename to source/reference/upgrade.txt index 57bb7b6c2..08a1f8753 100644 --- a/source/upgrade.txt +++ b/source/reference/upgrade.txt @@ -435,6 +435,16 @@ end-of-life (EOL). To learn more about the MongoDB support for EOL products, see the `Legacy Support Policy `__. +.. _java-server-8.1-incompatibility: + +Server Version 8.1 Support Changes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You cannot use a 3.x version of the {+driver-short+} to connect to a +deployment running {+mdb-server+} v8.1. Starting in {+mdb-server+} v8.1, +the ``buildinfo`` command requires authentication, causing an +incompatibility with the v3.x driver. + .. _java-server-release-change-v4.8: Version 4.8 Server Release Support Changes diff --git a/source/security.txt b/source/security.txt new file mode 100644 index 000000000..4414a7ffb --- /dev/null +++ b/source/security.txt @@ -0,0 +1,17 @@ +======== +Security +======== + +.. meta:: + :description: Learn how to use security features with the {+driver-long+}. + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Authentication + Enterprise Authentication + In-Use Encryption + TLS/SSL + SOCKS5 Proxy + Validate Driver Artifact Signatures \ No newline at end of file diff --git a/source/fundamentals/auth.txt b/source/security/auth.txt similarity index 98% rename from source/fundamentals/auth.txt rename to source/security/auth.txt index 59e2706a9..bad70bdc3 100644 --- a/source/fundamentals/auth.txt +++ b/source/security/auth.txt @@ -95,7 +95,7 @@ mechanism: .. code-block:: java - MongoClient mongoClient = MongoClients.create("mongodb://:@:/?authSource="); + MongoClient mongoClient = MongoClients.create("mongodb://:@:/?authSource="); .. tab:: :tabid: MongoCredential @@ -157,7 +157,7 @@ mechanism: .. code-block:: java - MongoClient mongoClient = MongoClients.create("mongodb://:@:/?authSource=&authMechanism=SCRAM-SHA-256"); + MongoClient mongoClient = MongoClients.create("mongodb://:@:/?authSource=&authMechanism=SCRAM-SHA-256"); .. tab:: :tabid: MongoCredential @@ -215,7 +215,7 @@ mechanism: .. code-block:: java - MongoClient mongoClient = MongoClients.create("mongodb://:@:/?authSource=&authMechanism=SCRAM-SHA-1"); + MongoClient mongoClient = MongoClients.create("mongodb://:@:/?authSource=&authMechanism=SCRAM-SHA-1"); .. tab:: :tabid: MongoCredential @@ -574,4 +574,4 @@ mechanism: For additional information on configuring your application to use certificates as well as TLS/SSL options, see our -:doc:`TLS/SSL guide `. \ No newline at end of file +:doc:`TLS/SSL guide `. \ No newline at end of file diff --git a/source/security/encrypt-fields.txt b/source/security/encrypt-fields.txt new file mode 100644 index 000000000..f26de05cf --- /dev/null +++ b/source/security/encrypt-fields.txt @@ -0,0 +1,28 @@ +.. _java-fle: + +.. sharedinclude:: dbx/encrypt-fields.rst + + .. replacement:: driver-specific-content + + .. important:: Compatible Encryption Library Version + + The {+driver-short+} uses the `mongodb-crypt + `__ + encryption library for in-use encryption. This driver version + is compatible with ``mongodb-crypt`` v{+mongocrypt-version+}. + + Select from the following :guilabel:`Maven` and + :guilabel:`Gradle` tabs to see how to add the ``mongodb-crypt`` + dependency to your project by using the specified manager: + + .. tabs:: + + .. tab:: Maven + :tabid: maven-dependency + + .. include:: /includes/fundamentals/code-snippets/crypt-maven-versioned.rst + + .. tab:: Gradle + :tabid: gradle-dependency + + .. include:: /includes/fundamentals/code-snippets/crypt-gradle-versioned.rst \ No newline at end of file diff --git a/source/fundamentals/enterprise-auth.txt b/source/security/enterprise-auth.txt similarity index 88% rename from source/fundamentals/enterprise-auth.txt rename to source/security/enterprise-auth.txt index 39b431a64..3dd449edb 100644 --- a/source/fundamentals/enterprise-auth.txt +++ b/source/security/enterprise-auth.txt @@ -63,7 +63,7 @@ principal name. The following code snippets show how to specify the authentication mechanism, using the following placeholders: -- ``username``: your URL-encoded principal name, such as ``"username%40REALM.ME"`` +- ``principal_username``: your URL-encoded principal name, such as ``"username%40REALM.ME"`` - ``hostname``: network address of your MongoDB deployment that your client can access - ``port``: port number of your MongoDB deployment @@ -92,7 +92,7 @@ mechanism: .. code-block:: java - MongoClient mongoClient = MongoClients.create("@:/?authSource=$external&authMechanism=GSSAPI"); + MongoClient mongoClient = MongoClients.create("@:/?authSource=$external&authMechanism=GSSAPI"); .. tab:: :tabid: MongoCredential @@ -151,7 +151,7 @@ You might need to specify one or more of the following additional .. code-block:: java - MongoClient mongoClient = MongoClients.create("@:/?authSource=$external&authMechanism=GSSAPI&authMechanismProperties=SERVICE_NAME:myService"); + MongoClient mongoClient = MongoClients.create("@:/?authSource=$external&authMechanism=GSSAPI&authMechanismProperties=SERVICE_NAME:myService"); .. tab:: :tabid: MongoCredential @@ -317,8 +317,9 @@ If your application runs on an Azure VM, or otherwise uses the support. You can specify Azure IMDS OIDC authentication either by -using a ``MongoCredential`` or as part of the connection string. Select the -:guilabel:`Connection String` or :guilabel:`MongoCredential` tab to +using a ``MongoCredential`` or as part of the connection string. + +Select from the :guilabel:`Connection String` or :guilabel:`MongoCredential` tabs to see the corresponding syntax. .. tabs:: @@ -326,27 +327,34 @@ see the corresponding syntax. .. tab:: Connection String :tabid: mongodb-azure-imds-connection-string - Replace the ```` placeholder with the percent-encoded - value of the ``audience`` server parameter configured on your MongoDB deployment. + Replace the ```` placeholder in the + following code with the percent-encoded value of the audience server + parameter configured on your MongoDB deployment. + + The comma (``,``) character and its encoding (``%2C``) are + reserved, and using these characters in a value causes the + driver to interpret commas as delimiters of key-value pairs. + You must specify values that contain commas in a ``MongoCredential`` instance, as + demonstrated in the :guilabel:`MongoCredential` tab. .. code-block:: java MongoClient mongoClient = MongoClients.create( - "mongodb://@:/?" + + "mongodb://@:/?" + "?authMechanism=MONGODB-OIDC" + "&authMechanismProperties=ENVIRONMENT:azure,TOKEN_RESOURCE:"); .. tab:: MongoCredential :tabid: mongodb-azure-mongo-credential - Replace the ```` placeholder with the client ID or application ID of the + Replace the ```` placeholder with the client ID or application ID of the Azure managed identity or enterprise application. Replace the ```` placeholder with the value of the ``audience`` server parameter configured on your MongoDB deployment. .. code-block:: java - MongoCredential credential = MongoCredential.createOidcCredential("") + MongoCredential credential = MongoCredential.createOidcCredential("") .withMechanismProperty("ENVIRONMENT", "azure") .withMechanismProperty("TOKEN_RESOURCE", ""); @@ -360,16 +368,17 @@ see the corresponding syntax. .. _java-mongodb-oidc-gcp-imds: GCP IMDS -++++++++++ +++++++++ -If your application runs on a GCP VM, or otherwise uses the +If your application runs on a Google Compute Engine VM, or otherwise uses the `GCP Instance Metadata Service `__, you can authenticate to MongoDB by using {+driver-short+}'s built-in GCP support. You can specify GCP IMDS OIDC authentication either by -using a ``MongoCredential`` or as part of the connection string. Select the -:guilabel:`Connection String` or :guilabel:`MongoCredential` tab to +using a ``MongoCredential`` or as part of the connection string. + +Select from the :guilabel:`Connection String` or :guilabel:`MongoCredential` tabs to see the corresponding syntax. .. tabs:: @@ -377,8 +386,15 @@ see the corresponding syntax. .. tab:: Connection String :tabid: mongodb-gcp-imds-connection-string - Replace the ```` placeholder with the percent-encoded - value of the ``audience`` server parameter configured on your MongoDB deployment. + Replace the ```` placeholder in the + following code with the percent-encoded value of the audience server + parameter configured on your MongoDB deployment. + + The comma (``,``) character and its encoding (``%2C``) are + reserved, and using these characters in a value causes the + driver to interpret commas as delimiters of key-value pairs. + You must specify values that contain commas in a ``MongoCredential`` instance, as + demonstrated in the :guilabel:`MongoCredential` tab. .. code-block:: java @@ -443,4 +459,4 @@ named ``"access-token.dat"`` in the local file system: .applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress("", )))) .credential(credential) - .build()); \ No newline at end of file + .build()); diff --git a/source/fundamentals/connection/socks.txt b/source/security/socks.txt similarity index 100% rename from source/fundamentals/connection/socks.txt rename to source/security/socks.txt diff --git a/source/fundamentals/connection/tls.txt b/source/security/tls.txt similarity index 99% rename from source/fundamentals/connection/tls.txt rename to source/security/tls.txt index d826373c2..a84d4ddec 100644 --- a/source/fundamentals/connection/tls.txt +++ b/source/security/tls.txt @@ -67,7 +67,7 @@ using a method in the ``MongoClientSettings.Builder`` class. .. code-block:: java - MongoClient mongoClient = MongoClients.create("mongodb+srv://:@?tls=true"); + MongoClient mongoClient = MongoClients.create("mongodb+srv://:@?tls=true"); .. tab:: MongoClientSettings :tabid: mongoclientsettings diff --git a/source/security/validate-signatures.txt b/source/security/validate-signatures.txt new file mode 100644 index 000000000..14fd28ee1 --- /dev/null +++ b/source/security/validate-signatures.txt @@ -0,0 +1,3 @@ +.. _java-validate-signatures: + +.. sharedinclude:: dbx/jvm/validate-artifacts.rst diff --git a/source/usage-examples.txt b/source/usage-examples.txt index c24426c69..f35cc0ecc 100644 --- a/source/usage-examples.txt +++ b/source/usage-examples.txt @@ -12,16 +12,15 @@ Usage Examples .. toctree:: - /usage-examples/find-operations - /usage-examples/insert-operations - /usage-examples/update-operations - /usage-examples/delete-operations - /usage-examples/bulkWrite - /usage-examples/watch - /usage-examples/count - /usage-examples/distinct - /usage-examples/command - + Find + Insert + Update & Replace + Delete + Bulk Operations + Watch for Changes + Count Documents + Distinct Field Values + Run a Command Overview -------- @@ -66,8 +65,8 @@ to learn how to allow connections to your instance of Atlas and to find the :manual:`connection string ` you use to replace the ``uri`` variable in usage examples. If your instance uses :manual:`SCRAM authentication `, you can replace -```` with your username, ```` with your password, and +```` with your database username, ```` with your database password, and ```` with the IP address or URL of your instance. For more information about connecting to your MongoDB instance, see our -:doc:`Connection Guide `. +:doc:`Connection Guide `. diff --git a/source/usage-examples/delete-operations.txt b/source/usage-examples/delete-operations.txt index f458f84e4..811d30db6 100644 --- a/source/usage-examples/delete-operations.txt +++ b/source/usage-examples/delete-operations.txt @@ -5,12 +5,11 @@ Delete Operations .. meta:: :description: Learn by example: how to delete data from MongoDB by using the {+driver-long+}. -- :doc:`Delete a Document ` -- :doc:`Delete Multiple Documents ` - .. toctree:: :caption: Examples - /usage-examples/deleteOne - /usage-examples/deleteMany - + Delete One + Delete Many + +- :doc:`Delete a Document ` +- :doc:`Delete Multiple Documents ` diff --git a/source/usage-examples/find-operations.txt b/source/usage-examples/find-operations.txt index 37c2dc28e..712144c6d 100644 --- a/source/usage-examples/find-operations.txt +++ b/source/usage-examples/find-operations.txt @@ -5,11 +5,11 @@ Find Operations .. meta:: :description: Learn by example: how to create queries and retrieve data from MongoDB by using the {+driver-long+}. -- :doc:`Find a Document ` -- :doc:`Find Multiple Documents ` - .. toctree:: :caption: Examples - /usage-examples/findOne - /usage-examples/find + Find One + Find Many + +- :doc:`Find a Document ` +- :doc:`Find Multiple Documents ` diff --git a/source/usage-examples/find.txt b/source/usage-examples/find.txt index ee9c93969..742732ba5 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 ca275c2ee..7270c2f00 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/usage-examples/insert-operations.txt b/source/usage-examples/insert-operations.txt index 77951e3e2..0c4b9975e 100644 --- a/source/usage-examples/insert-operations.txt +++ b/source/usage-examples/insert-operations.txt @@ -5,11 +5,11 @@ Insert Operations .. meta:: :description: Learn by example: how to insert data into MongoDB by using the {+driver-long+}. -- :doc:`Insert a Document ` -- :doc:`Insert Multiple Documents ` - .. toctree:: :caption: Examples - /usage-examples/insertOne - /usage-examples/insertMany + Insert One + Insert Many + +- :doc:`Insert a Document ` +- :doc:`Insert Multiple Documents ` diff --git a/source/usage-examples/update-operations.txt b/source/usage-examples/update-operations.txt index d09625d7f..0f8e93d37 100644 --- a/source/usage-examples/update-operations.txt +++ b/source/usage-examples/update-operations.txt @@ -5,13 +5,13 @@ Update & Replace Operations .. meta:: :description: Learn by example: how to update and replace data in MongoDB by using the {+driver-long+}. -- :doc:`Update a Document ` -- :doc:`Update Multiple Documents ` -- :doc:`Replace a Document ` - .. toctree:: :caption: Examples - /usage-examples/updateOne - /usage-examples/updateMany - /usage-examples/replaceOne + Update One + Update Many + Replace One + +- :doc:`Update a Document ` +- :doc:`Update Multiple Documents ` +- :doc:`Replace a Document ` diff --git a/source/usage-examples/updateMany.txt b/source/usage-examples/updateMany.txt index ce791efec..8385a1451 100644 --- a/source/usage-examples/updateMany.txt +++ b/source/usage-examples/updateMany.txt @@ -70,7 +70,7 @@ We use the ``Updates`` builder, a factory class that contains static helper methods to construct the update document. While you can pass an update document instead of using the builder, the builder provides type checking and simplified syntax. Read our -:doc:`guide on Updates ` in the Builders +:doc:`guide on Updates ` in the Builders section for more information. .. include:: /includes/connect-guide-note.rst diff --git a/source/usage-examples/updateOne.txt b/source/usage-examples/updateOne.txt index e8ce7eba2..f2696177f 100644 --- a/source/usage-examples/updateOne.txt +++ b/source/usage-examples/updateOne.txt @@ -69,7 +69,7 @@ We use the ``Updates`` builder, a factory class that contains static helper methods, to construct the update document. While you can pass an update document instead of using the builder, the builder provides type checking and simplified syntax. For more information about the ``Updates`` builder, see our -:doc:`guide on the Updates builder `. +:doc:`guide on the Updates builder `. .. include:: /includes/connect-guide-note.rst diff --git a/source/whats-new.txt b/source/whats-new.txt deleted file mode 100644 index df8264921..000000000 --- a/source/whats-new.txt +++ /dev/null @@ -1,677 +0,0 @@ -.. _java-whats-new: - -========== -What's New -========== - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: java sync, backwards compatibility, update, version - -.. contents:: On this page - :local: - :backlinks: none - :depth: 1 - :class: singlecol - -Learn what's new in: - -* :ref:`Version 5.1 ` -* :ref:`Version 5.0 ` -* :ref:`Version 4.11 ` -* :ref:`Version 4.10 ` -* :ref:`Version 4.9 ` -* :ref:`Version 4.8 ` -* :ref:`Version 4.7.1 ` -* :ref:`Version 4.7.0 ` -* :ref:`Version 4.6 ` -* :ref:`Version 4.5.1 ` -* :ref:`Version 4.5 ` -* :ref:`Version 4.4 ` -* :ref:`Version 4.3 ` -* :ref:`Version 4.2 ` -* :ref:`Version 4.1 ` -* :ref:`Version 4.0 ` - -.. _version-5.1: - -What's New in 5.1 ------------------ - -.. warning:: Deprecations in this release - - To avoid breaking changes in future major releases of the driver, - replace any application code that depends on deprecated program elements. - -This section includes the following information: - -- :ref:`java-deprecations-5.1` -- :ref:`java-improvements-5.1` -- :ref:`java-new-features-5.1` - -.. _java-deprecations-5.1: - -Deprecations in 5.1 -~~~~~~~~~~~~~~~~~~~ - -- Support for {+mdb-server+} v3.6 is deprecated and will be removed in the - next driver version release. To learn how to upgrade your {+mdb-server+} - deployment, see :manual:`Release Notes ` in the {+mdb-server+} - manual. - -.. _java-improvements-5.1: - -Improvements in 5.1 -~~~~~~~~~~~~~~~~~~~ - -- Internal testing of GraalVM native image technology. These tests involve building - native applications by using the GraalVM native-image tool. - -.. _java-new-features-5.1: - -New Features in 5.1 -~~~~~~~~~~~~~~~~~~~ - -- Introduces the ``serverMonitoringMode`` connection URI option. For more information about - this option, see the :ref:`connection-options` guide. - -.. _version-5.0: - -What's New in 5.0 ------------------ - -.. warning:: Breaking changes in this release - - This driver version introduces breaking changes. For a list of these changes, see - the :ref:`Version 5.0 Breaking Changes section ` in the - Upgrade guide. - -.. warning:: Deprecations in this release - - To avoid breaking changes in future major releases of the driver, - replace any application code that depends on deprecated program elements. - -This section includes the following information: - -- :ref:`java-deprecations-5.0` -- :ref:`java-behavioral-changes-5.0` -- :ref:`java-new-features-5.0` - -.. _java-deprecations-5.0: - -Deprecations in 5.0 -~~~~~~~~~~~~~~~~~~~ - -- The ``org.mongodb.scala.Observable.completeWithUnit()`` method is deprecated. - This method is not useful anymore because - the driver now exposes ``org.mongodb.scala.Observable[Unit]`` - instead of ``org.mongodb.scala.Observable[Void]``. - This relates to a :ref:`breaking change about Observables in this release - `. - -.. _java-behavioral-changes-5.0: - -Behavioral changes in 5.0 -~~~~~~~~~~~~~~~~~~~~~~~~~ - -- The ``getElapsedTime()`` method on ``com.mongodb.event.ConnectionReadyEvent`` - includes the time taken to deliver the ``ConnectionCreatedEvent``. That is, - the time returned includes the duration of the - ``com.mongodb.event.ConnectionPoolListener.connectionCreated()`` method. - - The ``getElapsedTime()`` methods on - ``com.mongodb.event.ConnectionCheckedOutFailedEvent`` and - ``com.mongodb.event.ConnectionCheckedOutEvent`` include the time taken to - deliver the ``com.mongodb.event.ConnectionCheckOutStartedEvent``. That is, the - time returned includes the duration of the - ``com.mongodb.eventConnectionPoolListener.connectionCheckOutStarted()`` method. - -.. _java-new-features-5.0: - -New features in 5.0 -~~~~~~~~~~~~~~~~~~~ - -The 5.0 driver release introduces the following features: - -- Adds support for the ``authorizedCollection`` option of - the ``listCollections`` command. This was done by changing the - ``com.mongodb.client.MongoDatabase.listCollectionNames()`` methods. - The return type is now ``com.mongodb.client.ListCollectionNamesIterable``, - while previously it was a ``MongoIterable``. - This change allows the return value to be - configured using the ``ListCollectionNamesIterable.authorizedCollections()`` - method and specifying the ``authorizedCollections`` option. Equivalent changes - were made to following classes and interfaces: - - - ``com.mongodb.reactivestreams.client.MongoDatabase`` - - ``org.mongodb.scala.MongoDatabase`` - - ``com.mongodb.kotlin.client.MongoDatabase`` - - ``com.mongodb.kotlin.client.coroutine.MongoDatabase`` - - These changes introduce a :ref:`binary breaking change to the listCollectionsNames() - method `. For more information - about the ``MongoDatabase.listCollectionNames()`` method and the - ``authorizedCollections`` option, see the - :manual:`listCollections ` Server manual - page or :ref:`java-collection-names`. - -.. _version-4.11: - -What's New in 4.11 ------------------- - -This section includes the following information: - -- :ref:`java-deprecations-4.11` -- :ref:`java-new-features-4.11` - -.. _java-deprecations-4.11: - -Deprecations in 4.11 -~~~~~~~~~~~~~~~~~~~~ - -.. warning:: Deprecations in this release - - To avoid breaking changes in future major releases of the driver, - replace any application code that depends on deprecated methods and types. - -The 4.11 driver release deprecates the following items: - -- The ``getStats()`` and ``isCapped()`` instance methods of the - ``DBCollection`` class are deprecated. The corresponding server - commands are deprecated in MongoDB v6.2 and later. Use the ``$collStats`` - aggregation pipeline stage to retrieve the information provided by these - methods instead. You can run the aggregation as shown in the following code - example: - - .. code-block:: java - - Cursor cursor = collection.aggregate(Arrays.asList( - new BasicDBObject("$collStats", - new BasicDBObject("storageStats", new BasicDBObject()))), - AggregationOptions.builder().build() - ); - - To determine whether a collection is a capped collection, access the value - of the ``storageStats.capped`` field returned by ``Cursor`` instance in the - preceding example aggregation. - - To learn more about the ``$collStats`` aggregation operator, see the - :manual:`$collStats (aggregation) ` - Server manual entry. - -- The following network address-related methods are deprecated and will be removed - in v5.0: - - - The `ServerAddress <{+api+}/apidocs/mongodb-driver-core/com/mongodb/ServerAddress.html>`__ - methods ``getSocketAddress()`` and ``getSocketAddresses()``. - - Instead of ``getSocketAddress()``, use the ``getByName()`` instance - method of ``java.net.InetAddress``. - - Instead of ``getSocketAddresses()``, use the ``getAllByName()`` instance - method of ``java.net.InetAddress``. - - - The `UnixServerAddress <{+api+}/apidocs/mongodb-driver-core/com/mongodb/UnixServerAddress.html>`__ - method ``getUnixSocketAddress()``. - - Instead of ``getUnixSocketAddress()``, construct an instance of - ``jnr.unixsocket.UnixSocketAddress``. Pass the full path of the UNIX - socket file to the constructor. By default, MongoDB creates a UNIX - socket file located at ``"/tmp/mongodb-27017.sock"``. To learn more - about the ``UnixSocketAddress``, see the `UnixSocketAddress `__ API documentation. - -- The following methods and types related to the - `StreamFactory `__ - interface are deprecated and scheduled for removal in v5.0: - - - ``streamFactoryFactory()`` method from ``MongoClientSettings.Builder`` - - ``getStreamFactoryFactory()`` method from ``MongoClientSettings`` - - ``NettyStreamFactoryFactory`` class - - ``NettyStreamFactory`` class - - ``AsynchronousSocketChannelStreamFactory`` class - - ``AsynchronousSocketChannelStreamFactoryFactory`` class - - ``BufferProvider`` class - - ``SocketStreamFactory`` class - - ``Stream`` class - - ``StreamFactory`` class - - ``StreamFactoryFactory`` class - - ``TlsChannelStreamFactoryFactory`` class - - If you configure Netty by using - ``MongoClientSettings.Builder.streamFactoryFactory()``, your code might resemble - the following: - - .. code-block:: java - :emphasize-lines: 6 - :copyable: false - - import com.mongodb.connection.netty.NettyStreamFactoryFactory; - - // ... - - MongoClientSettings settings = MongoClientSettings.builder() - .streamFactoryFactory(NettyStreamFactoryFactory.builder().build()) - .build(); - - Replace this code with the `TransportSettings.nettyBuilder() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/connection/TransportSettings.html>`__ - as shown in the following example: - - .. code-block:: java - :emphasize-lines: 6 - - import com.mongodb.connection.TransportSettings; - - // ... - - MongoClientSettings settings = MongoClientSettings.builder() - .transportSettings(TransportSettings.nettyBuilder().build()) - .build(); - -.. _java-new-features-4.11: - -New Features in 4.11 -~~~~~~~~~~~~~~~~~~~~ - -New features of the 4.11 driver release include: - -- Support for connecting to MongoDB by using a SOCKS5 proxy. To learn more - see :ref:`java-connect-socks`. -- Added the ``getSplitEvent()`` method to the ``ChangeStreamDocument`` class - to identify fragments of a change stream event that exceeds 16MB. You must - use the aggregation stage ``$changeStreamSplitLargeEvent`` in your change - stream to handle events that exceed 16MB. To learn more, see :ref:`java-split-change-stream-events`. -- Added an aggregation stage builder for ``$vectorSearch``. To learn more, see :ref:`Atlas Vector Search `. -- Added Atlas Search index management helpers. To learn more, see :ref:`Atlas Search Indexes `. -- Updated Snappy and Zstd compression library dependency versions. To learn - more about the current dependency versions, see :ref:`network-compression`. -- Added ``getElapsedTime()`` methods to the following classes to monitor the - duration of connection pool events: - - - `ConnectionCheckOutFailedEvent <{+api+}/apidocs/mongodb-driver-core/com/mongodb/event/ConnectionCheckOutFailedEvent.html>`__ - - `ConnectionCheckedOutEvent <{+api+}/apidocs/mongodb-driver-core/com/mongodb/event/ConnectionCheckedOutEvent.html>`__ - - `ConnectionReadyEvent <{+api+}/apidocs/mongodb-driver-core/com/mongodb/event/ConnectionReadyEvent.html>`__ - -- Support for Java 21 virtual threads and structured concurrency. The driver - internals were updated to avoid unnecessary pinning of virtual threads - and to preserve interrupted status of a thread, as the latter matters for - structured concurrency where it is used for cancellation. - - To learn more about virtual threads, see the `Virtual Threads `__ - JDK enhancement proposal. To learn more about structured concurrency, see the - `Structured Concurrency `__ - JDK enhancement proposal. - -- Updated API documentation for the following types: - - - `ClusterListener <{+api+}/apidocs/mongodb-driver-core/com/mongodb/event/ClusterListener.html>`__ - - `ServerListener <{+api+}/apidocs/mongodb-driver-core/com/mongodb/event/ServerListener.html>`__ - - `ServerMonitorListener <{+api+}/apidocs/mongodb-driver-core/com/mongodb/event/ServerMonitorListener.html>`__ - - -.. _version-4.10: - -What's New in 4.10 ------------------- - -New features of the 4.10 driver release include: - -- Implementation of the ``Accumulators.percentile()`` and - ``Accumulators.median()`` methods for statistical aggregations. -- Interfaces in the ``com.mongodb.client.model.search`` package are now - marked as ``@Sealed`` instead of ``@Evolving``. Sealed interfaces must - not be extended or implemented by consumers of the library. -- Resolved an issue where the driver emitted duplicate log messages for - retry operations. The driver now correctly emits one log message for - each retry operation. -- The ``org.bson.codecs.Parameterizable`` interface is deprecated. Instead of - implementing this interface on a custom ``Codec`` type, - override the ``CodecProvider.get()`` method on the - codec's ``CodecProvider`` if the codec is intended for a parameterized - type. -- Support for custom DNS resolvers. -- Support for :ref:`qe-manual-feature-qe` (QE). To learn - more about the requirements for using the QE feature, see the - :ref:`Queryable Encryption Driver Compatibility Table - `. - -.. _version-4.9: - -What's New in 4.9 ------------------ - -.. important:: Aggregation Expression Operations Are in Beta - - This driver version introduces an API for creating - :ref:`aggregation expressions `. - This feature is in beta phase. - -New features of the 4.9 driver release include: - -- Added a new exception to identify when a constructor annotated by - ``BsonCreator`` contains parameters with annotations other than - ``BsonProperty`` or ``BsonId``. -- Changed the log message format for command monitoring messages reported - by the ``org.mongodb.driver.protocol.command`` package. -- Added support for the ``$documents`` aggregation pipeline stage to the - `Aggregates <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Aggregates#documents(java.util.List)>`__ - helper class. -- Added `MongoClientSettings.Builder.applyToLoggerSettings() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html#applyToLoggerSettings(com.mongodb.Block)>`__ - and `LoggerSettings.Builder.maxDocumentLength() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/LoggerSettings.Builder.html#maxDocumentLength(int)>`__ - methods that let you specify a maximum length for the extended JSON representation of a - BSON document in a log message. - -.. _version-4.8: - -What's New in 4.8 ------------------ - -.. warning:: Breaking Changes in v4.8 - - The v4.8 driver contains breaking changes. See :ref:`` - and :ref:`` for more information. - -.. important:: Deprecation Notice - - The ``MapCodec`` and ``IterableCodec`` classes are deprecated. - Instead of ``MapCodec``, use ``MapCodecProvider``. Instead of ``IterableCodec``, - use ``CollectionCodecProvider``, or ``IterableCodecProvider`` for ``Iterable`` - types that aren't ``Collection`` types. - -Behavioral changes with the 4.8 driver release include: - -- Requirement that you add an explicit dependency on the ``org.bson.codecs.record`` - module if your application deploys the driver in an OSGi container and - relies on the driver for encoding and decoding Java records. -- Logging of new connection messages at the ``DEBUG`` level instead - of at ``INFO``. - -New features of the 4.8 driver release include: - -- Support for authentication with AWS. The driver takes an - optional dependency on both AWS SDK version 1 and version 2. -- Support for obtaining credentials from the environment for both GCP - and Azure for in-use encryption. -- Support for deserialization of records containing components with - generic parameters. -- Support for deserialization of records containing components with more - specific container types, such as ``SortedSet``, ``NavigableMap``, ``LinkedList``, - or ``TreeSet``. -- Support for recursive record types, records whose type - definitions contain cycles. -- Inclusion of the ``disambiguatedPaths`` field in change stream update events - when the ``showExpandedEvents`` server feature is enabled on MongoDB v6.1 - and later. Learn more about this field from the `getDisambiguatedPaths() `__ - API documentation. Learn more about the ``showExpandedEvents`` setting from - the :manual:`Expanded Events ` - server documentation. - -.. _version-4.7.1: -.. _version-4.7: - -What's New in 4.7.1 -------------------- - -The 4.7.1 driver patches a bug that affects -Client-Side Field Level Encryption and Queryable Encryption. -The bug can cause data corruption when rotating :ref:`Data Encryption Keys ` -(DEKs) encrypted with a :ref:`Customer Master Key ` -hosted on Google Cloud Key Management Service or Azure -Key Vault. The bug was present in version 4.7.0 of the driver -in the ``RewrapManyDataKey`` method and causes the -loss of your DEKs. - -.. important:: Back Up your Key Vault Collection - - Always back up your :ref:`Key Vault Collection ` - before you rotate your DEKs. If you lose your DEKs, you lose access to all - the data encrypted with those keys. - -.. _version-4.7.0: - -What's New in 4.7 ------------------ - -.. warning:: Breaking Changes in v4.7 - - The v4.7 driver contains breaking changes. See :ref:`` - for more information. - -New features of the 4.7 driver release include: - -- Added full support for MongoDB 6.0. - -- Added the following change stream support improvements: - - - Enhanced pre-image and post-image support for :ref:`change streams `. - Change stream watch helpers now accept ``whenAvailable`` and ``required`` - for the ``fullDocument`` option. See the :manual:`change stream ` - reference documentation for more information. - - Added a new ``fullDocumentBeforeChange`` option, which accepts - ``whenAvailable`` and ``required``. - - Change events now include a ``fullDocumentBeforeChange`` field - when configured for display on your MongoDB collection. - - Added ``showExpandedEvents`` support for change streams. - - Added ``wallTime`` support to the ``ChangeStreamDocument`` class. - -- Added :ref:`clustered index ` creation support. -- Support for new features related to :ref:`qe-manual-feature-qe`, - including support for automatic encryption (MongoDB v6.0 Enterprise or later - is required) and manual encryption. - - - Support for the new Queryable Encryption shared library, which removes the need - for the ``mongocryptd`` process. The queryable encryption shared library requires - `org.mongodb:mongodb-crypt `__ - version ``1.5.1.1`` or later. - -- Added a new API for encryption key management. - -- Added builder API methods for more aggregation stages - including :pipeline:`$search`/:pipeline:`$searchMeta` (Atlas only), - :pipeline:`$densify`, and :pipeline:`$fill`. Learn more about these - methods on the :ref:`Aggregates Builder ` page. - -- Added the ``BsonExtraElements`` annotation that can be used with POJO encoding - and decoding. ``BsonExtraElements`` enables decoding objects that might receive - new fields in the future without requiring developers to explicitly map - those new fields. - -- Performance optimizations including: - - - Lock-free implementations of the server session pool and the buffer pool. - - A new cleanup implementation of ``DBCursor`` that uses Java's - Cleaner API instead of finalization, available in Java 9 or later. - -- The :ref:`setWindowFields ` builder API - is no longer a beta feature. Changes in the API break both binary and source - compatibility. See :ref:`` for more information. - -.. _version-4.6: - -What's New in 4.6 ------------------ - -New features of the 4.6 Java driver release include: - -- The buffer pool is now shared across all ``MongoClient`` instances. The - buffer pool prunes buffers that have been idle for one minute. -- Added an API to specify suppliers for AWS KMS credentials for - Client-Side Field Level Encryption (CSFLE). See the - `AutoEncryptionSettings.Builder.kmsProviderPropertySuppliers() `__ - and the `ClientEncryptionSettings.Builder.kmsProviderPropertySuppliers() `__ - API documentation for more information. -- Added compatibility to ``org.mongodb:mongodb-crypt``, a dependency for - CSFLE, for Apple M1 ARM-based hardware. -- Added a service provider interface (SPI) to allow the driver to specify - a custom DNS client. See the `DnsClient `__ - and the `DnsClientProvider `__ - interface API documentation for more information. -- Added driver support for encoding and decoding between `Java records `__ - and BSON documents, which is enabled by default. See :ref:`` - for more information. - -.. _version-4.5: -.. _version-4.5.1: - -What's New in 4.5.1 -------------------- - -If the DNS server returns an NXDomain error, -indicating a non-existent domain, the 4.5.1 -driver no longer throws an exception. - -.. _version-4.5.0: - -What's New in 4.5 ------------------ - -New features of the 4.5 Java driver release include: - -- Added support for specifying custom service names of SRV resource - records. See the ``srvServiceName`` setting in the :ref:`Connection - Options ` guide for more information. -- Added support to customize UUID representation in a codec registry using - the ``CodecRegistries.withUuidRepresentation()`` method. -- Added support for overriding listener settings in ``ClusterSettings``, - ``ServerSettings`` and ``ConnectionPoolSettings`` builders. -- All events received by ``ClusterListener``, ``ServerListener``, and - ``ServerMonitorListener`` are now totally ordered using - a happens-before relationship when the listeners are not shared by - different MongoClient instances. To learn more about the happens-before - ordering, see `Happens-before Order `__ - in the Java Language Specification. -- Added ``EnumCodec`` and ``EnumCodecProvider`` classes to separate codec - support for ``enum`` types from the ``PojoCodec`` class. The default - codec registries, which you can access from the ``MongoClientSettings`` and the ``Bson`` - interfaces, now include the ``enum`` codec classes. If your application uses - a custom enumeration codec and one of the default registries, ensure - you order them as described in the section on :ref:`overriding codecs `. -- Resolved performance issues that impacted versions 4.4 and 4.3 of the - driver. Performance in this version is similar to performance in 4.2. -- Resolved an issue in which errors originating from retrieving the cluster - description weren't passed to the ``onError`` Subscriber callback -- Resolved an issue with releasing ``ByteBuf`` instances when you connect - with compression enabled. -- Removed an unnecessary dependency on the ``javax.annotation.*`` packages - from the ``org.mongodb.driver-core`` OSGi bundle. - -.. _version-4.4: - -What's New in 4.4 ------------------ - -New features of the 4.4 Java driver release include: - -- Compatibility with MongoDB 5.1 and support for Java 17 -- Added support for index hints in an ``AggregateIterable`` -- Added support for the ``$merge`` and ``$out`` aggregation stages on secondaries -- Use of the ``mergeObjects()`` method in the ``Updates`` builder -- ``DocumentCodec`` does not ignore a :ref:`CodecRegistry ` when writing to an ``Iterable`` or a ``Map`` instance - -.. _version-4.3: - -What's New in 4.3 ------------------ - -New features of the 4.3 Java driver release include: - -- Added support for the MongoDB {+stable-api+}. For more information, see our - :ref:`{+stable-api+} guide `. - - .. note:: - - Starting from February 2022, the **Versioned API** is known the - **{+stable-api+}**. All concepts and features remain the same with this - naming change. - -- Added support for connection to - `MongoDB Atlas Serverless Instances `__. - For more information about setup, see our documentation on how to - :atlas:`Create a New Serverless Instance ` -- Added a builder API for the ``setWindowFields`` pipeline stage to allow the use of window operators -- Added support for setting Netty `io.netty.handler.ssl.SslContext `__ -- Added support for snapshot reads to ``ClientSession`` -- Limited the rate of establishing new connections per connection pool -- Removed most restrictions on allowed characters in the field names of documents you insert or replace. This is a behavioral change for any application that is relying on client-side enforcement of these restrictions. - -The following table shows the restriction status on allowed characters -in the field names of documents: - -.. list-table:: - :header-rows: 1 - :stub-columns: 1 - :widths: 15 25 60 - - * - Character - - Operation - - Description - - * - **.** - - Insert and Replace - - Removed restrictions on field names containing this character. - - * - **$** - - Insert - - Removed restrictions on field names starting with this character. - - * - **$** - - Replace - - Removed restrictions in nested documents on field names containing this character. - - * - **$** - - Replace - - Kept restrictions in top-level documents on field names starting with this character. This prevents accidental use of a replace operation when the intention was to use an update operation. - -.. note:: - - Unacknowledged writes using dollar-prefixed or dotted keys might - be silently rejected by pre-5.0 servers, where some restrictions on - field names are still enforced in the server. - -.. _version-4.2: - -What's New in 4.2 ------------------ - -.. warning:: Breaking Changes in v4.2 - - The v4.2 driver contains breaking changes. See :ref:`` - for more information. - -New features of the 4.2 Java driver release include: - -- Added Azure and GCP key stores to client-side field level encryption -- Added Kerberos caching tickets for reuse in multiple authentication requests -- Added `MongoClients `_ instances with ``MongoClientSettings`` or ``ConnectionString`` as the configuration -- Use of the ``explain()`` method on `find `_ and `aggregate `_ commands -- Added a `JsonObject `_ class to make encoding from and decoding to JSON more efficient by avoiding an intermediate Map representation -- Added a `BsonRepresentation `_ annotation that allows you to represent the ``ObjectId`` BSON values as a ``String`` in `POJO `_ classes -- Added a `Filters.empty() `_ method - -.. _version-4.1: - -What's New in 4.1 ------------------ - -New features of the 4.1 Java driver release include: - -- Significant reduction in client-perceived failover times during planned maintenance events -- The `update() `_ and `delete() `_ methods now support index hints -- The ``find()`` method supports `allowDiskUse() `_ for sorts that require too much memory to execute in RAM -- Added support for the MONGODB-AWS authentication mechanism using Amazon Web Services (AWS) Identity and Access Management (IAM) credentials -- Authentication requires fewer round trips to the server, resulting in faster connection setup - -.. _version-4.0: - -What's New in 4.0 ------------------ - -.. warning:: Breaking Changes in v4.0 - - The v4.0 driver contains breaking changes. See :ref:`` - for more information. - -This release adds no new features.