From 6dc57931bd6885f260bbf47a3793f5390b41e168 Mon Sep 17 00:00:00 2001 From: shuangela Date: Mon, 7 Jul 2025 16:50:05 -0400 Subject: [PATCH 01/22] DOCSP-51351-reorganize-toc (#106) * reorg toc * Empty-Commit * fix links * fix link * Fix build errors * nr feedback * align with toc spreadsheet * fix quick bugs * add db coll section * fix file * fix typo * nr feedback --- config/redirects | 21 ++ source/aggregation.txt | 14 +- source/{ => aggregation}/agg-exp-ops.txt | 0 source/atlas-search.txt | 5 + source/atlas-vector-search.txt | 5 + source/connect.txt | 14 +- source/connect/connection-options.txt | 10 + source/connect/stable-api.txt | 6 +- source/crud.txt | 49 +++++ source/{write => crud}/bulk-write.txt | 0 source/crud/configure.txt | 11 + source/{write => crud}/delete.txt | 0 source/crud/gridfs.txt | 11 + source/{write => crud}/insert.txt | 0 source/crud/query.txt | 32 +++ source/{read => crud/query}/count.txt | 0 source/{read => crud/query}/cursors.txt | 0 source/{read => crud/query}/distinct.txt | 6 +- .../retrieve.txt => crud/query/find.txt} | 7 +- source/{read => crud/query}/project.txt | 0 .../{read => crud/query}/specify-a-query.txt | 0 .../query}/specify-documents-to-return.txt | 0 source/{write => crud}/replace.txt | 0 source/{write => crud}/transactions.txt | 6 +- source/{write => crud}/update.txt | 0 source/data-formats.txt | 9 +- source/data-formats/bson.txt | 6 +- source/data-formats/custom-types.txt | 26 +++ source/data-formats/serialization.txt | 6 +- source/data-formats/time-series.txt | 6 +- source/databases-collections.txt | 11 + source/get-started.txt | 6 +- source/index.txt | 117 ++++++----- source/indexes.txt | 6 +- source/issues-and-help.txt | 6 +- source/logging-and-monitoring.txt | 24 +++ .../change-streams.txt | 6 +- source/logging-and-monitoring/logging.txt | 9 + .../monitoring.txt | 6 +- source/read.txt | 156 --------------- source/reference.txt | 13 ++ source/{ => reference}/compatibility.txt | 6 +- source/reference/upgrade.txt | 11 + source/{ => reference}/whats-new.txt | 7 +- source/run-command.txt | 6 +- source/security.txt | 3 + source/{connect => security}/tls.txt | 6 +- source/{ => security}/validate-signatures.txt | 0 source/write-operations.txt | 188 ------------------ 49 files changed, 375 insertions(+), 462 deletions(-) rename source/{ => aggregation}/agg-exp-ops.txt (100%) create mode 100644 source/atlas-search.txt create mode 100644 source/atlas-vector-search.txt create mode 100644 source/crud.txt rename source/{write => crud}/bulk-write.txt (100%) create mode 100644 source/crud/configure.txt rename source/{write => crud}/delete.txt (100%) create mode 100644 source/crud/gridfs.txt rename source/{write => crud}/insert.txt (100%) create mode 100644 source/crud/query.txt rename source/{read => crud/query}/count.txt (100%) rename source/{read => crud/query}/cursors.txt (100%) rename source/{read => crud/query}/distinct.txt (98%) rename source/{read/retrieve.txt => crud/query/find.txt} (98%) rename source/{read => crud/query}/project.txt (100%) rename source/{read => crud/query}/specify-a-query.txt (100%) rename source/{read => crud/query}/specify-documents-to-return.txt (100%) rename source/{write => crud}/replace.txt (100%) rename source/{write => crud}/transactions.txt (98%) rename source/{write => crud}/update.txt (100%) create mode 100644 source/data-formats/custom-types.txt create mode 100644 source/databases-collections.txt create mode 100644 source/logging-and-monitoring.txt rename source/{read => logging-and-monitoring}/change-streams.txt (98%) create mode 100644 source/logging-and-monitoring/logging.txt rename source/{ => logging-and-monitoring}/monitoring.txt (99%) delete mode 100644 source/read.txt create mode 100644 source/reference.txt rename source/{ => reference}/compatibility.txt (95%) create mode 100644 source/reference/upgrade.txt rename source/{ => reference}/whats-new.txt (99%) rename source/{connect => security}/tls.txt (99%) rename source/{ => security}/validate-signatures.txt (100%) delete mode 100644 source/write-operations.txt diff --git a/config/redirects b/config/redirects index 9544ef3f..b2477918 100644 --- a/config/redirects +++ b/config/redirects @@ -10,3 +10,24 @@ symlink: current -> v5.5 raw: ${prefix}/ -> ${base}/current/ raw: ${prefix}/master -> ${base}/upcoming/ [v5.1-*]: ${prefix}/${version}/get-started/connect-to-mongodb -> ${base}/${version}/get-started/run-sample-query/ + +[*-master]: ${prefix}/${version}/connect/tls -> ${base}/${version}/security/tls +[*-master]: ${prefix}/${version}/write/insert -> ${base}/${version}/crud/insert +[*-master]: ${prefix}/${version}/write/update -> ${base}/${version}/crud/update +[*-master]: ${prefix}/${version}/write/delete -> ${base}/${version}/crud/delete +[*-master]: ${prefix}/${version}/write/bulk-write -> ${base}/${version}/crud/bulk-write +[*-master]: ${prefix}/${version}/write/replace -> ${base}/${version}/crud/replace +[*-master]: ${prefix}/${version}/write/transactions -> ${base}/${version}/crud/transactions +[*-master]: ${prefix}/${version}/read/specify-a-query -> ${base}/${version}/crud/query/specify-a-query +[*-master]: ${prefix}/${version}/read/retrieve -> ${base}/${version}/crud/query/find +[*-master]: ${prefix}/${version}/read/specify-documents-to-return -> ${base}/${version}/crud/query/specify-documents-to-return +[*-master]: ${prefix}/${version}/read/project -> ${base}/${version}/crud/query/project +[*-master]: ${prefix}/${version}/read/count -> ${base}/${version}/crud/query/count +[*-master]: ${prefix}/${version}/read/distinct -> ${base}/${version}/crud/query/distinct +[*-master]: ${prefix}/${version}/read/cursors -> ${base}/${version}/crud/query/cursors +[*-master]: ${prefix}/${version}/monitoring -> ${base}/${version}/logging-and-monitoring/monitoring +[*-master]: ${prefix}/${version}/read/change-streams -> ${base}/${version}/logging-and-monitoring/change-streams +[*-master]: ${prefix}/${version}/whats-new -> ${base}/${version}/reference/whats-new +[*-master]: ${prefix}/${version}/compatibility -> ${base}/${version}/reference/compatibility +[*-master]: ${prefix}/${version}/validate-signatures -> ${base}/${version}/security/validate-signatures +[*-master]: ${prefix}/${version}/agg-exp-ops -> ${base}/${version}/aggregation/agg-exp-ops \ No newline at end of file diff --git a/source/aggregation.txt b/source/aggregation.txt index 34592cf2..9fefce6b 100644 --- a/source/aggregation.txt +++ b/source/aggregation.txt @@ -1,8 +1,8 @@ .. _kotlin-sync-aggregation: -==================================== -Transform Your Data with Aggregation -==================================== +====================== +Aggregation Operations +====================== .. facet:: :name: genre @@ -18,9 +18,11 @@ Transform Your Data with Aggregation :depth: 2 :class: singlecol -.. .. toctree:: -.. :titlesonly: -.. :maxdepth: 1 +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Aggregation Expressions .. /aggregation/aggregation-tutorials diff --git a/source/agg-exp-ops.txt b/source/aggregation/agg-exp-ops.txt similarity index 100% rename from source/agg-exp-ops.txt rename to source/aggregation/agg-exp-ops.txt diff --git a/source/atlas-search.txt b/source/atlas-search.txt new file mode 100644 index 00000000..483dc91b --- /dev/null +++ b/source/atlas-search.txt @@ -0,0 +1,5 @@ +.. _kotlin-sync-atlas-search: + +========================= +Run an Atlas Search Query +========================= \ No newline at end of file diff --git a/source/atlas-vector-search.txt b/source/atlas-vector-search.txt new file mode 100644 index 00000000..cf6585fe --- /dev/null +++ b/source/atlas-vector-search.txt @@ -0,0 +1,5 @@ +.. _kotlin-sync-atlas-vector-search: + +================================ +Run an Atlas Vector Search Query +================================ \ No newline at end of file diff --git a/source/connect.txt b/source/connect.txt index 326c008d..cc47d76d 100644 --- a/source/connect.txt +++ b/source/connect.txt @@ -1,8 +1,8 @@ .. _kotlin-sync-connect: -================== -Connect to MongoDB -================== +================ +Connection Guide +================ .. contents:: On this page :local: @@ -24,14 +24,10 @@ Connect to MongoDB Create a MongoClient Choose a Connection Target - Connection Options - Limit Execution Time - Enable TLS - Stable API + Connection Options AWS Lambda -.. /connect/network-compression -.. /connect/server-selection +.. /connect/connection-troubleshooting Overview -------- diff --git a/source/connect/connection-options.txt b/source/connect/connection-options.txt index 3551bfe5..2c065e10 100644 --- a/source/connect/connection-options.txt +++ b/source/connect/connection-options.txt @@ -17,6 +17,16 @@ Specify Connection Options .. meta:: :keywords: connection string, URI, server, Atlas, settings, configure +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Stable API + Limit Server Execution Time + +.. /connect/network-compression +.. /connect/server-selection + Overview -------- diff --git a/source/connect/stable-api.txt b/source/connect/stable-api.txt index f7484c31..b58c0157 100644 --- a/source/connect/stable-api.txt +++ b/source/connect/stable-api.txt @@ -1,8 +1,8 @@ .. _kotlin-sync-stable-api: -============== -{+stable-api+} -============== +=========================== +Connect With {+stable-api+} +=========================== .. contents:: On this page :local: diff --git a/source/crud.txt b/source/crud.txt new file mode 100644 index 00000000..869d8e21 --- /dev/null +++ b/source/crud.txt @@ -0,0 +1,49 @@ +.. _kotlin-sync-crud-landing: +.. _kotlin-sync-crud-operations: +.. _kotlin-sync-write: +.. _kotlin-sync-read: + +=============== +CRUD Operations +=============== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :description: Learn how to use {+driver-short+} to read and write MongoDB data. + :keywords: usage examples, query, find, code example, save, create + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Insert Documents + Query Documents + Update Documents + Replace Documents + Delete Documents + Bulk Write Operations + Transactions + Configure CRUD Operations + Store Large Files + +CRUD (Create, Read, Update, Delete) operations enable you to work with +data stored in MongoDB. + +- :ref:`kotlin-sync-write-insert` +- :ref:`kotlin-sync-query` +- :ref:`kotlin-sync-write-update` +- :ref:`kotlin-sync-write-replace` +- :ref:`kotlin-sync-write-delete` +- :ref:`kotlin-sync-bulk-write` +- :ref:`kotlin-sync-write-transactions` +- :ref:`kotlin-sync-configure` +- :ref:`kotlin-sync-gridfs` \ No newline at end of file diff --git a/source/write/bulk-write.txt b/source/crud/bulk-write.txt similarity index 100% rename from source/write/bulk-write.txt rename to source/crud/bulk-write.txt diff --git a/source/crud/configure.txt b/source/crud/configure.txt new file mode 100644 index 00000000..f2e20e7b --- /dev/null +++ b/source/crud/configure.txt @@ -0,0 +1,11 @@ +.. _kotlin-sync-configure: + +========================= +Configure CRUD Operations +========================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol \ No newline at end of file diff --git a/source/write/delete.txt b/source/crud/delete.txt similarity index 100% rename from source/write/delete.txt rename to source/crud/delete.txt diff --git a/source/crud/gridfs.txt b/source/crud/gridfs.txt new file mode 100644 index 00000000..1dbb1b00 --- /dev/null +++ b/source/crud/gridfs.txt @@ -0,0 +1,11 @@ +.. _kotlin-sync-gridfs: + +================= +Store Large Files +================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol \ No newline at end of file diff --git a/source/write/insert.txt b/source/crud/insert.txt similarity index 100% rename from source/write/insert.txt rename to source/crud/insert.txt diff --git a/source/crud/query.txt b/source/crud/query.txt new file mode 100644 index 00000000..4302e94d --- /dev/null +++ b/source/crud/query.txt @@ -0,0 +1,32 @@ +.. _kotlin-sync-query: + +=============== +Query Documents +=============== + +.. meta:: + :description: Learn how to use {+driver-short+} to read data from MongoDB. + :keywords: usage examples, query, find, code example + +.. facet:: + :name: genre + :values: reference + +.. toctree:: + :maxdepth: 1 + + Find Documents + Specify Documents to Return + Specify Fields to Return + Specify a Query + Count Documents + Distinct Field Values + Access Data from a Cursor + +- :ref:`kotlin-sync-find` +- :ref:`kotlin-sync-specify-documents-to-return` +- :ref:`kotlin-sync-project` +- :ref:`kotlin-sync-specify-query` +- :ref:`kotlin-sync-count` +- :ref:`kotlin-sync-distinct` +- :ref:`kotlin-sync-cursors` \ No newline at end of file diff --git a/source/read/count.txt b/source/crud/query/count.txt similarity index 100% rename from source/read/count.txt rename to source/crud/query/count.txt diff --git a/source/read/cursors.txt b/source/crud/query/cursors.txt similarity index 100% rename from source/read/cursors.txt rename to source/crud/query/cursors.txt diff --git a/source/read/distinct.txt b/source/crud/query/distinct.txt similarity index 98% rename from source/read/distinct.txt rename to source/crud/query/distinct.txt index fbb0f834..6f510318 100644 --- a/source/read/distinct.txt +++ b/source/crud/query/distinct.txt @@ -1,8 +1,8 @@ .. _kotlin-sync-distinct: -============================== -Retrieve Distinct Field Values -============================== +===================== +Distinct Field Values +===================== .. contents:: On this page :local: diff --git a/source/read/retrieve.txt b/source/crud/query/find.txt similarity index 98% rename from source/read/retrieve.txt rename to source/crud/query/find.txt index ff5f73db..e51ae9b5 100644 --- a/source/read/retrieve.txt +++ b/source/crud/query/find.txt @@ -1,8 +1,9 @@ .. _kotlin-sync-retrieve: +.. _kotlin-sync-find: -============= -Retrieve Data -============= +============== +Find Documents +============== .. contents:: On this page :local: diff --git a/source/read/project.txt b/source/crud/query/project.txt similarity index 100% rename from source/read/project.txt rename to source/crud/query/project.txt diff --git a/source/read/specify-a-query.txt b/source/crud/query/specify-a-query.txt similarity index 100% rename from source/read/specify-a-query.txt rename to source/crud/query/specify-a-query.txt diff --git a/source/read/specify-documents-to-return.txt b/source/crud/query/specify-documents-to-return.txt similarity index 100% rename from source/read/specify-documents-to-return.txt rename to source/crud/query/specify-documents-to-return.txt diff --git a/source/write/replace.txt b/source/crud/replace.txt similarity index 100% rename from source/write/replace.txt rename to source/crud/replace.txt diff --git a/source/write/transactions.txt b/source/crud/transactions.txt similarity index 98% rename from source/write/transactions.txt rename to source/crud/transactions.txt index aa5fb55e..0bdd4178 100644 --- a/source/write/transactions.txt +++ b/source/crud/transactions.txt @@ -1,8 +1,8 @@ .. _kotlin-sync-write-transactions: -============ -Transactions -============ +========================= +Transactions and Sessions +========================= .. contents:: On this page :local: diff --git a/source/write/update.txt b/source/crud/update.txt similarity index 100% rename from source/write/update.txt rename to source/crud/update.txt diff --git a/source/data-formats.txt b/source/data-formats.txt index 14b9b934..b1cad2cd 100644 --- a/source/data-formats.txt +++ b/source/data-formats.txt @@ -1,8 +1,8 @@ .. _kotlin-sync-data-formats: -======================== -Specialized Data Formats -======================== +============ +Data Formats +============ .. contents:: On this page :local: @@ -21,9 +21,8 @@ Specialized Data Formats :titlesonly: :maxdepth: 1 + Custom Types Data Classes - Kotlin Serialization - Codecs BSON Time Series diff --git a/source/data-formats/bson.txt b/source/data-formats/bson.txt index 86f882b8..c512f9c8 100644 --- a/source/data-formats/bson.txt +++ b/source/data-formats/bson.txt @@ -1,8 +1,8 @@ .. _kotlin-sync-bson: -==== -BSON -==== +=================== +Work with BSON Data +=================== .. contents:: On this page :local: diff --git a/source/data-formats/custom-types.txt b/source/data-formats/custom-types.txt new file mode 100644 index 00000000..f63c08e7 --- /dev/null +++ b/source/data-formats/custom-types.txt @@ -0,0 +1,26 @@ +.. _kotlin-sync-custom-types: + +================= +Custom Data Types +================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :description: Learn how to use the Kotlin Sync driver to encode and decode custom types, including defining type codecs, using type registries, and implementing fallback encoders. + :keywords: bson, uuid, date, time + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Serialization + Type Codecs \ No newline at end of file diff --git a/source/data-formats/serialization.txt b/source/data-formats/serialization.txt index fd211fee..adac7f91 100644 --- a/source/data-formats/serialization.txt +++ b/source/data-formats/serialization.txt @@ -1,8 +1,8 @@ .. _kotlin-sync-serialization: -==================== -Kotlin Serialization -==================== +================== +Data Serialization +================== .. facet:: :name: genre diff --git a/source/data-formats/time-series.txt b/source/data-formats/time-series.txt index 09321d12..62894248 100644 --- a/source/data-formats/time-series.txt +++ b/source/data-formats/time-series.txt @@ -1,8 +1,8 @@ .. _kotlin-sync-time-series: -================ -Time Series Data -================ +======================= +Time Series Collections +======================= .. contents:: On this page :local: diff --git a/source/databases-collections.txt b/source/databases-collections.txt new file mode 100644 index 00000000..3f85571e --- /dev/null +++ b/source/databases-collections.txt @@ -0,0 +1,11 @@ +.. _kotlin-sync-db-collections: + +========================= +Databases and Collections +========================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol \ No newline at end of file diff --git a/source/get-started.txt b/source/get-started.txt index a54c0c12..94ff61f6 100644 --- a/source/get-started.txt +++ b/source/get-started.txt @@ -1,8 +1,8 @@ .. _kotlin-sync-get-started: -======================================= -Get Started with the Kotlin Sync Driver -======================================= +=========== +Get Started +=========== .. contents:: On this page :local: diff --git a/source/index.txt b/source/index.txt index e76b60ce..f02e7482 100644 --- a/source/index.txt +++ b/source/index.txt @@ -13,24 +13,23 @@ .. toctree:: - Get Started + Getting Started Connect - Write Data - Read Data - Indexes - Data Aggregation - Aggregation Operations - Specialized Data Formats + Databases & Collections + CRUD Operations + Aggregation Builders - Run a Command - Monitoring + Data Formats + Indexes + Run a Database Command + Atlas Search + Atlas Vector Search + Logging and Monitoring Security - Compatibility - Validate Driver Signatures - What's New + Reference + API Documentation Issues & Help View the Source - API Documentation Introduction ------------ @@ -58,67 +57,85 @@ Connect to MongoDB Learn how to create and configure a connection to a MongoDB deployment in the :ref:`kotlin-sync-connect` section. -Write Data to MongoDB ---------------------- +Databases and Collections +------------------------- -Learn how you can write data to MongoDB in the :ref:`kotlin-sync-write` section. +Learn how to interact with MongoDB databases and collections in the +:ref:`kotlin-sync-db-collections` section. -Read Data ---------- +Read and Write Data +------------------- -Learn how you can retrieve data from MongoDB in the :ref:`kotlin-sync-read` section. - -Optimize Queries with Indexes ------------------------------ - -Learn how to work with common types of indexes in the :ref:`kotlin-sync-indexes` -section. +Learn how to find, update, and delete data in the :ref:`kotlin-sync-crud-landing` section. Transform Your Data with Aggregation ------------------------------------- +------------------------------------- Learn how to use the {+driver-short+} to perform aggregation operations in the :ref:`kotlin-sync-aggregation` section. -Learn how to use aggregation expression operations to build -aggregation stages in the :ref:`kotlin-sync-aggregation-expression-operations` section. +Builders +-------- + +Learn how to use builder classes to efficiently build queries and aggregations in the +:ref:`kotlin-sync-builders` section. -Specialized Data Formats ------------------------- +Data Formats +------------ -Learn how to work with specialized data formats and custom types in the +Learn how to work with BSON and other data formats in the :ref:`kotlin-sync-data-formats` section. -Use Builders API ----------------- +Optimize Queries with Indexes +----------------------------- -Learn how to work with the builder operation helpers in the :ref:`kotlin-sync-builders` section. +Learn how to work with common types of indexes in the :ref:`kotlin-sync-indexes` section. -Compatibility -------------- +Run a Database Command +---------------------- + +Learn how to run a database command in the :ref:`kotlin-run-command` section. + +Atlas Search +------------ + +Learn how to run Atlas Search queries in the :ref:`kotlin-sync-atlas-search` section. + +Atlas Vector Search +------------------- -For the compatibility charts that show the recommended {+driver-short+} version for each -MongoDB Server version, see the :ref:`Compatibility -` section. +Learn how to run Atlas Vector Search queries in the :ref:`kotlin-sync-atlas-vector-search` section. -Validate Driver Artifact Signatures ------------------------------------ +Logging and Monitoring +---------------------- + +Learn how to monitor changes to your application and write them to logs in the +:ref:`kotlin-sync-logging-monitoring` section. + +Secure Your Data +---------------- + +Learn about ways you can authenticate your application and encrypt your data in +the :ref:`kotlin-sync-security` section. + +Reference +--------- -Learn about how to validate signatures of {+driver-short+} artifacts -published on Maven in the :ref:`Validate Driver Artifact Signatures ` section. +Find more information about {+driver-short+} versions, compatibility, and third-party tools in the +:ref:`kotlin-sync-reference` section. -What's New ----------- +API Documentation +----------------- -For a list of new features and changes in each version, see the -:ref:`What's New ` section. +For detailed information about classes and methods in the MongoDB +Node.js driver, see the `{+driver-long+} API documentation +<{+driver-api+}>`__. Issues & Help ------------- -Learn how to report bugs, contribute to the driver, and find more resources for -asking questions and receiving help in the :ref:`Issues & Help -` section. +Learn how to report bugs, contribute to the driver, and to find help in the +:ref:`kotlin-sync-issues-and-help` section. Learn ------ diff --git a/source/indexes.txt b/source/indexes.txt index 7a1bf0b3..9e866d92 100644 --- a/source/indexes.txt +++ b/source/indexes.txt @@ -1,8 +1,8 @@ .. _kotlin-sync-indexes: -================================= -Optimize Queries by Using Indexes -================================= +============================== +Indexes for Query Optimization +============================== .. contents:: On this page :local: diff --git a/source/issues-and-help.txt b/source/issues-and-help.txt index 6f360e9d..9293b5d7 100644 --- a/source/issues-and-help.txt +++ b/source/issues-and-help.txt @@ -1,8 +1,8 @@ .. _kotlin-sync-issues-and-help: -============= -Issues & Help -============= +============================ +Report Issues & Request Help +============================ .. facet:: :name: genre diff --git a/source/logging-and-monitoring.txt b/source/logging-and-monitoring.txt new file mode 100644 index 00000000..16c8c6c9 --- /dev/null +++ b/source/logging-and-monitoring.txt @@ -0,0 +1,24 @@ +.. _kotlin-sync-logging-monitoring: + +====================== +Logging and Monitoring +====================== + +.. facet:: + :name: programming_language + :values: kotlin + +.. meta:: + :keywords: event + +.. toctree:: + + Monitoring + Logging + Change Streams + +Overview +-------- + +On this page, you can see copyable code examples that show common +methods you can use to monitor and log events with {+driver-short+}. \ No newline at end of file diff --git a/source/read/change-streams.txt b/source/logging-and-monitoring/change-streams.txt similarity index 98% rename from source/read/change-streams.txt rename to source/logging-and-monitoring/change-streams.txt index 7d293f91..7d41df95 100644 --- a/source/read/change-streams.txt +++ b/source/logging-and-monitoring/change-streams.txt @@ -1,8 +1,8 @@ .. _kotlin-sync-change-streams: -==================== -Monitor Data Changes -==================== +================================ +Monitor Data with Change Streams +================================ .. contents:: On this page :local: diff --git a/source/logging-and-monitoring/logging.txt b/source/logging-and-monitoring/logging.txt new file mode 100644 index 00000000..5ad75e51 --- /dev/null +++ b/source/logging-and-monitoring/logging.txt @@ -0,0 +1,9 @@ +================= +Log Driver Events +================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol \ No newline at end of file diff --git a/source/monitoring.txt b/source/logging-and-monitoring/monitoring.txt similarity index 99% rename from source/monitoring.txt rename to source/logging-and-monitoring/monitoring.txt index d400b1ff..3485417b 100644 --- a/source/monitoring.txt +++ b/source/logging-and-monitoring/monitoring.txt @@ -1,6 +1,6 @@ -========== -Monitoring -========== +========================== +Monitor Application Events +========================== .. contents:: On this page :local: diff --git a/source/read.txt b/source/read.txt deleted file mode 100644 index 615a73a6..00000000 --- a/source/read.txt +++ /dev/null @@ -1,156 +0,0 @@ -.. _kotlin-sync-read: - -========= -Read Data -========= - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :description: Learn how to use the Kotlin Sync Driver to read data from MongoDB. - :keywords: usage examples, query, find, code example - -.. toctree:: - :titlesonly: - :maxdepth: 1 - - Specify a Query - Retrieve Data - Specify Fields to Return - Specify Documents to Return - Count Documents - Distinct Field Values - Data Cursors - Monitor Data Changes - -Overview --------- - -On this page, you can see copyable code examples that show common -methods you can use to retrieve documents by using the {+driver-short+}. - -.. tip:: - - To learn more about any of the methods shown on this page, see the link - to a relevant guide provided in each section. - -To use an example from this page, copy the code example into the -:ref:`sample application ` or your own application. -Be sure to replace all placeholders in the code examples, such as ````, with -the relevant values for your MongoDB deployment. - -.. _kotlin-sync-read-sample: - -.. include:: /includes/usage-examples/sample-app-intro.rst - -.. literalinclude:: /includes/usage-examples/sample-app.kt - :language: kotlin - :copyable: - :linenos: - :emphasize-lines: 20-22 - -.. tip:: - - For instructions about how to install the {+driver-short+}, see :ref:``. - -Find Documents --------------- - -The following example retrieves a list of documents that match the criteria specified by the -given filter: - -.. literalinclude:: /includes/usage-examples/retrieve-code-examples.kt - :start-after: start-find - :end-before: end-find - :language: kotlin - :copyable: - :dedent: - -To learn more about the ``find()`` method, see the :ref:`kotlin-sync-retrieve-find` guide. - -Count Documents in a Collection -------------------------------- - -The following example returns the number of documents in the specified collection: - -.. literalinclude:: /includes/usage-examples/retrieve-code-examples.kt - :start-after: start-count-all - :end-before: end-count-all - :language: kotlin - :copyable: - :dedent: - -To learn more about the ``countDocuments()`` method, see the -:ref:`kotlin-sync-accurate-count` section of the Count Documents guide. - -Count Documents Returned from a Query -------------------------------------- - -The following example returns the number of documents that match the criteria specified by -the given filter: - -.. literalinclude:: /includes/usage-examples/retrieve-code-examples.kt - :start-after: start-count-query - :end-before: end-count-query - :language: kotlin - :copyable: - :dedent: - -To learn more about the ``countDocuments()`` method, see the -:ref:`kotlin-sync-accurate-count` section of the Count Documents guide. - -Estimated Document Count ------------------------- - -The following example returns an approximate number of documents in the specified -collection based on collection metadata: - -.. literalinclude:: /includes/usage-examples/retrieve-code-examples.kt - :start-after: start-estimated-count - :end-before: end-estimated-count - :language: kotlin - :copyable: - :dedent: - -To learn more about the ``estimatedDocumentCount()`` method, see the -:ref:`kotlin-sync-estimated-count` section of the Count Documents guide. - -Retrieve Distinct Values ------------------------- - -The following example returns all distinct values of the specified field name in a given -collection: - -.. literalinclude:: /includes/usage-examples/retrieve-code-examples.kt - :start-after: start-distinct - :end-before: end-distinct - :language: kotlin - :copyable: - :dedent: - -To learn more about the ``distinct()`` method, see the -:ref:`kotlin-sync-distinct` guide. - -Monitor Data Changes --------------------- - -The following example creates a change stream for a given collection and prints out -subsequent change events in that collection: - -.. literalinclude:: /includes/usage-examples/retrieve-code-examples.kt - :start-after: start-watch - :end-before: end-watch - :language: kotlin - :copyable: - :dedent: - -To learn more about the ``watch()`` method, see the -:ref:`kotlin-sync-change-streams` guide. \ No newline at end of file diff --git a/source/reference.txt b/source/reference.txt new file mode 100644 index 00000000..fcc9dfe2 --- /dev/null +++ b/source/reference.txt @@ -0,0 +1,13 @@ +.. _kotlin-sync-reference: + +========== +Reference +========== + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Release Notes + Compatibility + Upgrade \ No newline at end of file diff --git a/source/compatibility.txt b/source/reference/compatibility.txt similarity index 95% rename from source/compatibility.txt rename to source/reference/compatibility.txt index c931f398..c3738226 100644 --- a/source/compatibility.txt +++ b/source/reference/compatibility.txt @@ -1,8 +1,8 @@ .. _kotlin-sync-compatibility: -============= -Compatibility -============= +==================== +Driver Compatibility +==================== .. contents:: On this page :local: diff --git a/source/reference/upgrade.txt b/source/reference/upgrade.txt new file mode 100644 index 00000000..d1c97a35 --- /dev/null +++ b/source/reference/upgrade.txt @@ -0,0 +1,11 @@ +.. _kotlin-sync-upgrade: + +======================= +Upgrade Driver Versions +======================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol \ No newline at end of file diff --git a/source/whats-new.txt b/source/reference/whats-new.txt similarity index 99% rename from source/whats-new.txt rename to source/reference/whats-new.txt index ca689dd1..73e9f230 100644 --- a/source/whats-new.txt +++ b/source/reference/whats-new.txt @@ -1,8 +1,9 @@ .. _kotlin-sync-whats-new: +.. _kotlin-sync-release-notes: -========== -What's New -========== +============= +Release Notes +============= .. contents:: On this page :local: diff --git a/source/run-command.txt b/source/run-command.txt index cae850da..0f0568ef 100644 --- a/source/run-command.txt +++ b/source/run-command.txt @@ -1,8 +1,8 @@ .. _kotlin-run-command: -============= -Run a Command -============= +====================== +Run a Database Command +====================== .. contents:: On this page :local: diff --git a/source/security.txt b/source/security.txt index 08969d5b..5c605dcb 100644 --- a/source/security.txt +++ b/source/security.txt @@ -1,3 +1,4 @@ +.. _kotlin-sync-security: ================ Secure Your Data @@ -7,8 +8,10 @@ Secure Your Data :titlesonly: :maxdepth: 1 + TLS Authentication Enterprise Authentication In-Use Encryption + Validate Driver Artifact Signatures .. placeholder \ No newline at end of file diff --git a/source/connect/tls.txt b/source/security/tls.txt similarity index 99% rename from source/connect/tls.txt rename to source/security/tls.txt index 3bb8aebf..6c9dc453 100644 --- a/source/connect/tls.txt +++ b/source/security/tls.txt @@ -1,8 +1,8 @@ .. _kotlin-sync-tls: -========================== -Enable TLS on a Connection -========================== +============================== +Enable TLS/SSL on a Connection +============================== .. facet:: :name: genre diff --git a/source/validate-signatures.txt b/source/security/validate-signatures.txt similarity index 100% rename from source/validate-signatures.txt rename to source/security/validate-signatures.txt diff --git a/source/write-operations.txt b/source/write-operations.txt deleted file mode 100644 index 6e2d02c0..00000000 --- a/source/write-operations.txt +++ /dev/null @@ -1,188 +0,0 @@ -.. _kotlin-sync-write: - -===================== -Write Data to MongoDB -===================== - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :description: Learn how to use the Kotlin Sync driver to write data to MongoDB. - :keywords: usage examples, save, crud, create, code example - -.. toctree:: - :titlesonly: - :maxdepth: 1 - - Insert - Update - Replace - Delete - Bulk Write - Transactions - -.. - /write/gridfs - -Overview --------- - -On this page, you can see copyable code examples of common -methods that you can use to write data to MongoDB by using the -{+driver-short+}. - -.. tip:: - - To learn more about any of the methods shown on this page, see the link - provided in each section. - -To use an example from this page, copy the code example into the -:ref:`sample application ` or your own application. -Be sure to replace all placeholders in the code examples, such as ````, with -the relevant values for your MongoDB deployment. - -.. _kotlin-sync-write-sample: - -.. include:: /includes/usage-examples/sample-app-intro.rst - -.. literalinclude:: /includes/usage-examples/sample-app.kt - :language: kotlin - :copyable: - :linenos: - :emphasize-lines: 20-22 - -Insert One ----------- - -The following code shows how to insert a single document into a -collection: - -.. literalinclude:: /includes/usage-examples/write-code-examples.kt - :start-after: start-insert-one - :end-before: end-insert-one - :language: kotlin - :copyable: - :dedent: - -To learn more about the ``insertOne()`` method, see the :ref:`Insert Documents -` guide. - -Insert Multiple ---------------- - -The following code shows how to insert multiple documents into a -collection: - -.. literalinclude:: /includes/usage-examples/write-code-examples.kt - :start-after: start-insert-multiple - :end-before: end-insert-multiple - :language: kotlin - :copyable: - :dedent: - -To learn more about the ``insertMany()`` method, see the :ref:`Insert Documents -` guide. - -Update One ----------- - -The following code shows how to update a single document in a -collection by creating or editing a field: - -.. literalinclude:: /includes/usage-examples/write-code-examples.kt - :start-after: start-update-one - :end-before: end-update-one - :language: kotlin - :copyable: - :dedent: - -To learn more about the ``updateOne()`` method, see the -:ref:`Update Documents ` guide. - -Update Multiple ---------------- - -The following code shows how to update multiple documents in a -collection by creating or editing a field: - -.. literalinclude:: /includes/usage-examples/write-code-examples.kt - :start-after: start-update-multiple - :end-before: end-update-multiple - :language: kotlin - :copyable: - :dedent: - -To learn more about the ``updateMany()`` method, see the -:ref:`Update Documents ` guide. - -Replace One ------------ - -The following code shows how to replace a single document in a -collection with a new document: - -.. literalinclude:: /includes/usage-examples/write-code-examples.kt - :start-after: start-replace-one - :end-before: end-replace-one - :language: kotlin - :copyable: - :dedent: - -To learn more about the ``replaceOne()`` method, see the -:ref:`Replace Documents ` guide. - -Delete One ----------- - -The following code shows how to delete a single document in a -collection: - -.. literalinclude:: /includes/usage-examples/write-code-examples.kt - :start-after: start-delete-one - :end-before: end-delete-one - :language: kotlin - :copyable: - :dedent: - -To learn more about the ``deleteOne()`` method, see the -:ref:`Delete Documents ` guide. - -Delete Multiple ---------------- - -The following code shows how to delete multiple documents in a -collection: - -.. literalinclude:: /includes/usage-examples/write-code-examples.kt - :start-after: start-delete-multiple - :end-before: end-delete-multiple - :language: kotlin - :copyable: - :dedent: - -To learn more about the ``deleteMany()`` method, see the -:ref:`Delete Documents ` guide. - -Bulk Write ----------- - -The following code shows how to perform multiple write operations in a -single bulk operation: - -.. literalinclude:: /includes/usage-examples/write-code-examples.kt - :start-after: start-bulk-write - :end-before: end-bulk-write - :language: kotlin - :copyable: - :dedent: - -To learn more about the ``bulkWrite()`` method, see the -:ref:`Bulk Write ` guide. From 426571490f7a32f537610208d764a29cf8afc83a Mon Sep 17 00:00:00 2001 From: Michael Morisi Date: Wed, 9 Jul 2025 09:42:59 -0400 Subject: [PATCH 02/22] DOCSP-51320: Document causal consistency (#108) --- source/crud/transactions.txt | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/source/crud/transactions.txt b/source/crud/transactions.txt index 0bdd4178..a44ade6d 100644 --- a/source/crud/transactions.txt +++ b/source/crud/transactions.txt @@ -47,6 +47,35 @@ creating a new client each time. ``ClientSession`` with a different ``MongoClient`` results in operation errors. +Causal Consistency +~~~~~~~~~~~~~~~~~~ + +.. sharedinclude:: dbx/causal-consistency.rst + + .. replacement:: insert-one-method + + ``insertOne()`` + + .. replacement:: update-one-method + + ``updateOne()`` + + .. replacement:: find-one-method + + ``find()`` + + .. replacement:: delete-one-method + + ``deleteOne()`` + + .. replacement:: majority-rc + + ``ReadConcern.MAJORITY`` + + .. replacement:: majority-wc + + ``WriteConcern.MAJORITY`` + Sample Data ~~~~~~~~~~~ From d70ee6318ad4b28d3cea2523fb7676a8101fe497 Mon Sep 17 00:00:00 2001 From: shuangela Date: Wed, 9 Jul 2025 14:04:01 -0400 Subject: [PATCH 03/22] add logging overview (#112) --- source/logging-and-monitoring.txt | 8 ++++++-- source/logging-and-monitoring/logging.txt | 2 ++ source/logging-and-monitoring/monitoring.txt | 2 ++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/source/logging-and-monitoring.txt b/source/logging-and-monitoring.txt index 16c8c6c9..4aa780f6 100644 --- a/source/logging-and-monitoring.txt +++ b/source/logging-and-monitoring.txt @@ -20,5 +20,9 @@ Logging and Monitoring Overview -------- -On this page, you can see copyable code examples that show common -methods you can use to monitor and log events with {+driver-short+}. \ No newline at end of file +Learn how to set up logging and monitoring for your application in +the following sections: + +- :ref:`Logging ` +- :ref:`Monitoring ` +- :ref:`Change Streams ` \ No newline at end of file diff --git a/source/logging-and-monitoring/logging.txt b/source/logging-and-monitoring/logging.txt index 5ad75e51..ee9285ea 100644 --- a/source/logging-and-monitoring/logging.txt +++ b/source/logging-and-monitoring/logging.txt @@ -1,3 +1,5 @@ +.. _kotlin-sync-logging: + ================= Log Driver Events ================= diff --git a/source/logging-and-monitoring/monitoring.txt b/source/logging-and-monitoring/monitoring.txt index 3485417b..eaac9ebc 100644 --- a/source/logging-and-monitoring/monitoring.txt +++ b/source/logging-and-monitoring/monitoring.txt @@ -1,3 +1,5 @@ +.. _kotlin-sync-monitoring: + ========================== Monitor Application Events ========================== From 546c88ea7c0354bfde866176891eb00fb54758b2 Mon Sep 17 00:00:00 2001 From: Michael Morisi Date: Thu, 10 Jul 2025 09:11:39 -0400 Subject: [PATCH 04/22] DOCSP-51345: Document polling SRV records (#107) --- source/connect/connection-targets.txt | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/source/connect/connection-targets.txt b/source/connect/connection-targets.txt index f0332efd..f84f30c4 100644 --- a/source/connect/connection-targets.txt +++ b/source/connect/connection-targets.txt @@ -122,3 +122,14 @@ The following examples show how to connect to a MongoDB replica set running on p .. note:: Replica Set in Docker .. sharedinclude:: dbx/docker-replica-set.rst + +DNS Service Discovery +--------------------- + +.. sharedinclude:: dbx/srv-polling.rst + + .. replacement:: srv-uri + + .. code-block:: kotlin + + val uri = "mongodb+srv:///" \ No newline at end of file From d56dcd3983826574bf9d87040dcd5c53ae196334 Mon Sep 17 00:00:00 2001 From: shuangela Date: Mon, 14 Jul 2025 12:02:47 -0400 Subject: [PATCH 05/22] DOCSP-51326-add-find-one (#114) * add find one * fix code * edit code * add table entries * formatting * monospace * mw feedback --- source/crud/query/find.txt | 37 ++++++++++++++++++++++++++++++++ source/includes/read/retrieve.kt | 9 ++++++++ 2 files changed, 46 insertions(+) diff --git a/source/crud/query/find.txt b/source/crud/query/find.txt index e51ae9b5..32f2ada3 100644 --- a/source/crud/query/find.txt +++ b/source/crud/query/find.txt @@ -53,6 +53,36 @@ collection. To learn more about query filters, see the :ref:`kotlin-sync-specify-query` guide. +Find One Document Example +~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example chains the ``first()`` method to the ``find()`` method call to find +the first document in which the value of the ``cuisine`` field is ``"Spanish"``: + +.. literalinclude:: /includes/read/retrieve.kt + :start-after: start-find-one + :end-before: end-find-one + :language: kotlin + :copyable: + :dedent: + +The ``find()`` operation in the preceding example returns a MongoDB document, which you +can print, as shown in the following example: + +.. io-code-block:: + :copyable: true + + .. input:: /includes/read/retrieve.kt + :start-after: start-find-one-print + :end-before: end-find-one-print + :language: kotlin + :dedent: + + .. output:: + :visible: false + + Restaurant(name=Tropicoso Club, cuisine=Spanish) + Find Documents Example ~~~~~~~~~~~~~~~~~~~~~~ @@ -124,6 +154,13 @@ modifying queries: - | Specifies a string to attach to the query. This can help you trace and interpret the operation in the server logs and in profile data. + * - ``first()`` + - | Returns the first document that matches the query or throws a ``MongoClientException`` + if no matching documents exist. + + * - ``firstOrNull()`` + - | Returns the first document that matches the query or ``null`` if no matching documents exist. + * - ``hint()`` - | Specifies the index to use for the query. diff --git a/source/includes/read/retrieve.kt b/source/includes/read/retrieve.kt index 6a9df06c..e7774ae2 100644 --- a/source/includes/read/retrieve.kt +++ b/source/includes/read/retrieve.kt @@ -26,6 +26,10 @@ fun main() { val results = collection.find(eq(Restaurant::cuisine.name, "Spanish")) // end-find + // start-find-one + val results = collection.find(eq(Restaurant::cuisine.name, "Spanish")).first() + // end-find-one + // start-find-iterate val results = collection.find(eq(Restaurant::cuisine.name, "Spanish")) results.forEach { result -> @@ -33,6 +37,11 @@ fun main() { } // end-find-iterate + // start-find-one-print + val results = collection.find(eq(Restaurant::cuisine.name, "Spanish")).first() + println(results) + // end-find-one-print + // start-find-all val results = collection.find() // end-find-all From 3bfbf9c5969b35278c935f728d90aea6a638d75c Mon Sep 17 00:00:00 2001 From: shuangela Date: Tue, 15 Jul 2025 10:54:59 -0400 Subject: [PATCH 06/22] DOCSP-51408-connection-troubleshooting (#109) * connection troubleshooting: * fix typos/broken links * lm feedback * fix toc * fix toc again * attempt error fix * Fix toc * Fix build error --- snooty.toml | 8 +- source/connect.txt | 7 +- source/connect/connection-options.txt | 9 +- source/connect/connection-pools.txt | 16 + source/connect/connection-targets.txt | 2 + source/connect/connection-troubleshooting.txt | 308 ++++++++++++++++++ 6 files changed, 335 insertions(+), 15 deletions(-) create mode 100644 source/connect/connection-pools.txt create mode 100644 source/connect/connection-troubleshooting.txt diff --git a/snooty.toml b/snooty.toml index 1f20e7e9..752e3cee 100644 --- a/snooty.toml +++ b/snooty.toml @@ -8,14 +8,16 @@ intersphinx = [ ] toc_landing_pages = [ - "/write-operations", - "/read", "/connect", "/indexes", - "work-with-indexes", + "/work-with-indexes", "/data-formats", "/builders", "/aggregation", + "/connect/connection-options", + "/logging-and-monitoring", + "/databases-and-collections", + "/api" ] sharedinclude_root = "https://raw.githubusercontent.com/10gen/docs-shared/main/" diff --git a/source/connect.txt b/source/connect.txt index cc47d76d..ca6d1a99 100644 --- a/source/connect.txt +++ b/source/connect.txt @@ -19,15 +19,12 @@ Connection Guide :keywords: client, ssl, tls, localhost .. toctree:: - :titlesonly: - :maxdepth: 1 Create a MongoClient Choose a Connection Target - Connection Options + Connection Options AWS Lambda - -.. /connect/connection-troubleshooting + Connection Troubleshooting Overview -------- diff --git a/source/connect/connection-options.txt b/source/connect/connection-options.txt index 2c065e10..f01765be 100644 --- a/source/connect/connection-options.txt +++ b/source/connect/connection-options.txt @@ -4,12 +4,6 @@ Specify Connection Options ========================== -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - .. facet:: :name: genre :values: reference @@ -23,9 +17,10 @@ Specify Connection Options Stable API Limit Server Execution Time + Connection Pools .. /connect/network-compression -.. /connect/server-selection +.. /connect/server-selection Overview -------- diff --git a/source/connect/connection-pools.txt b/source/connect/connection-pools.txt new file mode 100644 index 00000000..e8b95f19 --- /dev/null +++ b/source/connect/connection-pools.txt @@ -0,0 +1,16 @@ +.. _kotlin-sync-connection-pools: + +================ +Connection Pools +================ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + + +.. _kotlin-sync-connection-pool-settings: + +.. TODO \ No newline at end of file diff --git a/source/connect/connection-targets.txt b/source/connect/connection-targets.txt index f84f30c4..80ac95ab 100644 --- a/source/connect/connection-targets.txt +++ b/source/connect/connection-targets.txt @@ -70,6 +70,8 @@ deployment: :end-before: end-connect-local :dedent: +.. _kotlin-sync-connect-replica-set: + Replica Sets ------------ diff --git a/source/connect/connection-troubleshooting.txt b/source/connect/connection-troubleshooting.txt new file mode 100644 index 00000000..06fe1a59 --- /dev/null +++ b/source/connect/connection-troubleshooting.txt @@ -0,0 +1,308 @@ +.. _kotlin-sync-connection-troubleshooting: + +========================== +Connection Troubleshooting +========================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example, disconnected, deployment + +.. sharedinclude:: dbx/connection-troubleshooting.rst + + .. replacement:: non-connection-issue-callout + + .. note:: + + 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 :community-forum:`MongoDB Community Forums ` for + questions, discussions, or general technical support + + .. replacement:: server-selection-timeout-error + + .. code-block:: none + :copyable: false + + Error: couldn't connect to server 127.0.0.1:27017 + + .. replacement:: check-connection-string-anchor + + .. _kotlin-sync-connection-string-port: + + .. replacement:: multiple-hosts-connection-guide-link + + To learn how to specify multiple replica set hosts, see the + :ref:`kotlin-sync-connect-replica-set` section of the Connection Guide. + + .. replacement:: configure-firewall-anchor + + .. _kotlin-sync-connection-firewall: + + .. replacement:: authentication-error-anchor + + .. _kotlin-sync-authentication-error: + + .. replacement:: scram-failure-error + + .. code-block:: none + :copyable: false + + Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server localhost:27017. + + .. replacement:: check-credentials-formatting-anchor + + .. _kotlin-sync-connection-string-auth: + + .. replacement:: learn-more-connection-string-admonition + + .. tip:: + + For more information about using connection strings, + see :ref:`Connection URI ` in the Connection Guide. + + .. replacement:: percent-encode-example + + .. replacement:: verify-authentication-database-anchor + + .. _kotlin-sync-verify-auth-db: + + .. replacement:: credentials-provider-alternative-method-description + + If you construct a client by using a ``MongoCredential``, the builder method + corresponds to the authentication mechanism. The following code shows the builder + method for the ``SCRAM-SHA-256`` authentication mechanism: + + .. code-block:: kotlin + :copyable: false + + val credential = MongoCredential.createScramSha256Credential( + "", "", "".toCharArray() + ) + + val settings = MongoClientSettings.builder() + .applyToClusterSettings { builder: ClusterSettings.Builder -> + builder.hosts( + listOf(ServerAddress("", )) + ) + } + .credential(credential) + .build() + + val mongoClient = MongoClient.create(settings) + + .. replacement:: authentication-guide-reference + + To learn more about specifying authentication mechanisms, see the :ref:`kotlin-sync-auth` + section. + + .. replacement:: verify-authentication-mechanism-anchor + + .. _kotlin-sync-verify-auth-mechanism: + + .. replacement:: authsource-param-code-block + + .. code-block:: kotlin + :copyable: false + + val mongoClient = MongoClient.create("mongodb://:@:/?authSource=users"); + + .. replacement:: dns-resolution-anchor + + .. _kotlin-sync-dns-resolution-error: + + .. replacement:: dns-error-message + + .. code-block:: none + :copyable: false + + com.mongodb.MongoSocketWriteException: Exception sending message + + .. replacement:: check-the-number-of-connections-anchor + + .. _kotlin-sync-connection-num-connections: + + .. replacement:: mongo-client-class + + ``MongoClient`` + + .. replacement:: max-pool-size-param + + ``maxPoolSize`` + + .. replacement:: max-pool-size-default + + ``100`` + + .. replacement:: max-idle-time-param + + ``maxIdleTimeMS`` + + .. replacement:: scram-failure-error + + .. code-block:: + + Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server localhost:27017. + + .. replacement:: check-credentials-formatting-anchor + + .. _kotlin-sync-troubleshooting-connection-string-auth: + + .. replacement:: connection-pools-learn-more + + To learn more about how connection pooling works in the driver, see the + :ref:`Connection Pools ` page. + +.. _kotlin-sync-timeout-errors: + +Timeout Errors +-------------- + +When you send messages through the driver to the server, sometimes the +messages take a while to respond. When this happens, you might receive an error +message similar to one of the following messages: + +.. code-block:: none + :copyable: false + + Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. + +.. code-block:: none + :copyable: false + + No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description + +If you receive one of these errors, try the following methods to resolve the +issue. + +Set ``maxConnectionTimeoutMS`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The ``maxConnectionTimeoutMS`` option indicates the time the {+driver-short+} waits +for a connection before timing out. The default value is ``10000``. You can +increase this value or set it to ``0`` if you want the driver to never timeout. + +Set ``maxConnectionLifeTime`` and ``maxConnectionIdleTime`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Consider setting ``maxConnectionLifeTime`` and +``maxConnectionIdleTime``. These parameters configure how long the driver +maintains a connection to a MongoDB instance. For more information about these +parameters, see :ref:`Connection Pool Settings `. + +.. _kotlin-sync-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:`kotlin-sync-connection-options` guide. + +.. _kotlin-sync-miscellaneous-errors: + +Miscellaneous Errors +-------------------- + +This section shows connection errors that do not fall into a broader category. + +Monitor Thread Exception +~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: none + :copyable: false + + INFO: Exception in monitor thread while connecting to server ssc-cluster-01-shard-00-02.9cbnp.mongodb.net:27017 + +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 +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: none + :copyable: false + + javax.net.ssl.SSLHandshakeException: extension (5) should not be presented in certificate_request + +This is a known issue in certain versions of the JDK that can occur when +attempting to connect by using the TLS 1.3 protocol. + +If you encounter this error when connecting to your MongoDB instance or +cluster, update your JDK to one of the following patch versions or newer: + +- JDK 11.0.7 +- JDK 13.0.3 +- JDK 14.0.2 + +To learn more about this issue, see the +`issue description `__ +in the OpenJDK Bug system tracker issue. + +.. _kotlin-sync-debugging-tips: + +Debugging Tips +-------------- + +While not related to a specific error message, this section includes +information that can help in the process of troubleshooting connection +issues. + +Verbose Logging for TLS/SSL +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can use the ``-Djavax.net.debug=all`` system property to enable +debug-level logging related to all connections, including those +established by using TLS/SSL. + +Enabling debug-level logging can help you diagnose the root problem of +connection issues. To learn more about the TLS/SSL logging messages, +see the `Debugging SSL/TLS Connections `__ +Java documentation. \ No newline at end of file From 294b18cca10758086e19961dbd947e8f139366b9 Mon Sep 17 00:00:00 2001 From: Nora Reidy Date: Wed, 16 Jul 2025 13:42:36 -0400 Subject: [PATCH 07/22] DOCSP-51323: Databases & collections (#111) * DOCSP-51323: Databases & collections * code fix * edits * link fix * NH feedback --- source/databases-collections.txt | 185 ++++++++++++++++++++++- source/includes/databases-collections.kt | 47 ++++++ 2 files changed, 231 insertions(+), 1 deletion(-) create mode 100644 source/includes/databases-collections.kt diff --git a/source/databases-collections.txt b/source/databases-collections.txt index 3f85571e..2f53c0f2 100644 --- a/source/databases-collections.txt +++ b/source/databases-collections.txt @@ -8,4 +8,187 @@ Databases and Collections :local: :backlinks: none :depth: 2 - :class: singlecol \ No newline at end of file + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: table, row, organize, storage, code example + +Overview +-------- + +In this guide, you can learn how to use MongoDB databases and +collections with the {+driver-short+}. + +MongoDB organizes data into a hierarchy of the following levels: + +- **Databases**: Top-level data structures in a MongoDB deployment that store collections. +- **Collections**: Groups of MongoDB documents. They are analogous to tables in relational databases. +- **Documents**: Units that store literal data such as string, numbers, dates, and other embedded documents. + For more information about document field types and structure, see the + :manual:`Documents ` guide in the {+mdb-server+} manual. + +Access a Database +----------------- + +To access a database, pass the database name to the ``getDatabase()`` +method. + +The following example accesses a database named ``test_database``: + +.. literalinclude:: /includes/databases-collections.kt + :language: kotlin + :dedent: + :start-after: start-access-database + :end-before: end-access-database + +.. _kotlin-sync-db-coll-access-collection: + +Access a Collection +------------------- + +To access a collection, pass the database name to the ``getCollection()`` +method. + +The following example accesses a collection named ``test_collection``: + +.. literalinclude:: /includes/databases-collections.kt + :language: kotlin + :dedent: + :start-after: start-access-collection + :end-before: end-access-collection + +.. tip:: + + If the provided collection name does not already exist in the database, + MongoDB implicitly creates the collection when you first insert data + into it. + +.. _kotlin-sync-db-coll-create-collection: + +Create a Collection +------------------- + +To explicitly create a collection in a MongoDB database, pass a collection +name to the ``createCollection()`` method. + +The following example creates a collection named ``example_collection``: + +.. literalinclude:: /includes/databases-collections.kt + :language: kotlin + :dedent: + :start-after: start-create-collection + :end-before: end-create-collection + +You can specify collection options, such as maximum size and document +validation rules, by setting them in a ``CreateCollectionOptions`` instance. +Then, pass the ``CreateCollectionOptions`` to the ``createCollection()`` method. +For a full list of optional parameters, see the `CreateCollectionOptions <{+core-api+}/client/model/CreateCollectionOptions.html>`__ +API documentation. + +Get a List of Collections +------------------------- + +You can query for a list of collections in a database by calling the +``listCollections()`` method. The method returns a cursor containing all +collections in the database and their associated metadata. + +The following example calls the ``listCollections()`` method and iterates over +the returned iterator to print the collections from the :ref:`kotlin-sync-db-coll-access-collection` +and :ref:`kotlin-sync-db-coll-create-collection` examples: + +.. io-code-block:: + :copyable: true + + .. input:: /includes/databases-collections.kt + :language: kotlin + :start-after: start-find-collections + :end-before: end-find-collections + :dedent: + + .. output:: + + { + "name": "example_collection", + "type": "collection", + "options": {}, + "info": { + "readOnly": false, + ... + }, + "idIndex": { ... } + } + { + "name": "test_collection", + "type": "collection", + "options": {}, + "info": { + "readOnly": false, + ... + }, + "idIndex": { ... } + } + +Delete a Collection +------------------- + +To delete a collection from the database, call the ``drop()`` method +on your collection. + +The following example deletes the ``test_collection`` collection: + +.. literalinclude:: /includes/databases-collections.kt + :language: kotlin + :dedent: + :start-after: start-drop-collection + :end-before: end-drop-collection + +.. warning:: Dropping a Collection Deletes All Data in the Collection + + Dropping a collection from your database permanently deletes all + documents and all indexes within that collection. + + Drop a collection only if you no longer need the data in it. + +.. _kotlin-sync-config-read-write: + +Configure Read and Write Operations +----------------------------------- + +You can control how read and write operations run on replica sets +by specifying a read preference, read concern, or write concern. + +By default, databases inherit read and write settings from the ``MongoClient`` +instance. Collections inherit these settings from the ``MongoClient`` or +``MongoDatabase`` instance on which the ``getCollection()`` method is called. +You can change these settings by calling the following methods: + +- `MongoDatabase.withReadConcern() <{+driver-api+}/-mongo-database/with-read-concern.html>`__ + +- `MongoDatabase.withReadPreference() <{+driver-api+}/-mongo-database/with-read-preference.html>`__ + +- `MongoDatabase.withWriteConcern() <{+driver-api+}/-mongo-database/with-write-concern.html>`__ + +- `MongoCollection.withReadConcern() <{+driver-api+}/-mongo-collection/with-read-concern.html>`__ + +- `MongoCollection.withReadPreference() <{+driver-api+}/-mongo-collection/with-read-preference.html>`__ + +- `MongoCollection.withWriteConcern() <{+driver-api+}/-mongo-collection/with-write-concern.html>`__ + +To learn more about setting a read preference, read concern, and write concern, +see the :ref:`kotlin-sync-configure` guide. + +API Documentation +----------------- + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- `getDatabase() <{+driver-api+}/-mongo-cluster/get-database.html>`__ +- `getCollection() <{+driver-api+}/-mongo-database/get-collection.html>`__ +- `createCollection() <{+driver-api+}/-mongo-database/create-collection.html>`__ +- `listCollections() <{+driver-api+}/-mongo-database/list-collections.html>`__ +- `drop() <{+driver-api+}/-mongo-collection/drop.html>`__ \ No newline at end of file diff --git a/source/includes/databases-collections.kt b/source/includes/databases-collections.kt new file mode 100644 index 00000000..d045ebb2 --- /dev/null +++ b/source/includes/databases-collections.kt @@ -0,0 +1,47 @@ +import com.mongodb.ConnectionString +import com.mongodb.MongoClientSettings +import com.mongodb.kotlin.client.MongoClient +import org.bson.Document +import org.bson.json.JsonWriterSettings + +fun main() { + val uri = "" + + val settings = MongoClientSettings.builder() + .applyConnectionString(ConnectionString(uri)) + .retryWrites(true) + .build() + + val client = MongoClient.create(settings) + + // Accesses the "test_database" database + // start-access-database + val db = client.getDatabase("test_database") + // end-access-database + + // Accesses the "test_collection" collection + // start-access-collection + val collection = db.getCollection("test_collection") + // end-access-collection + + // Explicitly creates the "example_collection" collection + // start-create-collection + db.createCollection("example_collection") + // end-create-collection + + // Lists the collections in the "test_database" database + // start-find-collections + val results = db.listCollections() + val jsonSettings = JsonWriterSettings.builder().indent(true).build() + + results.forEach { result -> + println(result.toJson(jsonSettings)) + } + // end-find-collections + + + // Deletes the "test_collection" collection + // start-drop-collection + db.getCollection("test_collection").drop() + // end-drop-collection +} From 7c94562fbe9afeb16613188351da479466937e6f Mon Sep 17 00:00:00 2001 From: Nora Reidy Date: Wed, 16 Jul 2025 13:42:50 -0400 Subject: [PATCH 08/22] DOCSP-51341: Extended JSON (#116) * DOCSP-51341: Extended JSON * snooty * edits * build errors * NH feedback --- source/data-formats.txt | 7 +- source/data-formats/extended-json.txt | 198 +++++++++++++++++++++++ source/includes/data-formats/ext-json.kt | 105 ++++++++++++ 3 files changed, 305 insertions(+), 5 deletions(-) create mode 100644 source/data-formats/extended-json.txt create mode 100644 source/includes/data-formats/ext-json.kt diff --git a/source/data-formats.txt b/source/data-formats.txt index b1cad2cd..c553d5af 100644 --- a/source/data-formats.txt +++ b/source/data-formats.txt @@ -25,8 +25,7 @@ Data Formats Data Classes BSON Time Series - -.. TODO: /data-formats/extended-json + Extended JSON Overview -------- @@ -49,6 +48,4 @@ sections: :ref:`kotlin-sync-data-format-data-classes` guide. - Learn how to work with the BSON data format in the :ref:`kotlin-sync-bson` guide. - Learn how to store and interact with time series data in the :ref:`kotlin-sync-time-series` guide. - -.. TODO: Uncomment these as pages get built -.. - Learn how to use the Extended JSON format in the :ref:`kotlin-sync-extended-json` guide. +- Learn how to read and write Extended JSON strings in the :ref:`kotlin-sync-extended-json` guide. diff --git a/source/data-formats/extended-json.txt b/source/data-formats/extended-json.txt new file mode 100644 index 00000000..9795a17d --- /dev/null +++ b/source/data-formats/extended-json.txt @@ -0,0 +1,198 @@ +.. _kotlin-sync-extended-json: + +============================ +Work with Extended JSON Data +============================ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code examples, bson, relaxed, canonical + +.. sharedinclude:: dbx/extended-json.rst + + .. replacement:: driver-specific-text-extended + + .. replacement:: driver-specific-text-relaxed + + The {+driver-short+} uses Relaxed mode by default. + + .. replacement:: driver-specific-text-shell + +Read Extended JSON +------------------ + +This section shows how to read Extended JSON values into {+language+} +objects in the following ways: + +- :ref:`kotlin-sync-read-ejson-doc` +- :ref:`kotlin-sync-read-ejson-jsonreader` + +.. _kotlin-sync-read-ejson-doc: + +Use the Document Classes +~~~~~~~~~~~~~~~~~~~~~~~~ + +To read a Extended JSON string into a {+language+} document object, call +the ``parse()`` static method from the ``Document`` or ``BsonDocument`` class. +This method parses the Extended JSON string and stores its data in an instance of the specified +document class. + +The following example uses the ``parse()`` method to read an Extended JSON string +into a ``Document`` object: + +.. io-code-block:: + :copyable: + + .. input:: /includes/data-formats/ext-json.kt + :language: kotlin + :start-after: start-read-doc + :end-before: end-read-doc + :dedent: + + .. output:: + :visible: false + + Document{{_id=507f1f77bcf86cd799439011, myNumber=4794261}} + +.. _kotlin-sync-read-ejson-jsonreader: + +Use the JsonReader Class +~~~~~~~~~~~~~~~~~~~~~~~~ + +To read an Extended JSON string into {+language+} objects without using +the {+driver-short+}'s document classes, use the BSON library's ``JsonReader`` class. +This class contains methods to sequentially parse the fields and values +of the Extended JSON string and return them as {+language+} objects. +The driver's document classes also use this class to parse Extended JSON. + +The following code uses methods provided by the ``JsonReader`` class to convert +an Extended JSON string into {+language+} objects: + +.. io-code-block:: + :copyable: + + .. input:: /includes/data-formats/ext-json.kt + :language: kotlin + :start-after: start-read-bson + :end-before: end-read-bson + :dedent: + + .. output:: + :visible: false + + 507f1f77bcf86cd799439011 is type: org.bson.types.ObjectId + 4794261 is type: kotlin.Long + +Write Extended JSON +------------------- + +This section shows how to write Extended JSON values from {+language+} +objects in the following ways: + +- :ref:`kotlin-sync-write-ejson-doc` +- :ref:`kotlin-sync-write-ejson-jsonwriter` + +.. _kotlin-sync-write-ejson-doc: + +Use the Document Classes +~~~~~~~~~~~~~~~~~~~~~~~~ + +To write an Extended JSON string from a ``Document`` or ``BsonDocument`` +object, call the ``toJson()`` method. You can pass this method a +``JsonWriterSettings`` object parameter to specify the Extended JSON format. + +The following example writes ``Document`` data as Relaxed mode Extended +JSON: + +.. io-code-block:: + :copyable: + + .. input:: /includes/data-formats/ext-json.kt + :language: kotlin + :start-after: start-write-doc + :end-before: end-write-doc + :dedent: + + .. output:: + :visible: false + + {"_id": {"$oid": "507f1f77bcf86cd799439012"}, "createdAt": {"$date": "2020-09-30T21:00:09Z"}, "myNumber": 4794261} + +.. _kotlin-sync-write-ejson-jsonwriter: + +Use the JsonWriter Class +~~~~~~~~~~~~~~~~~~~~~~~~ + +To output an Extended JSON string from data stored in {+language+} objects, you can use +the BSON library's ``JsonWriter`` class. To construct a ``JsonWriter`` object, +pass a subclass of a Java ``Writer`` to specify how you want to output the Extended +JSON. Optionally, you can pass a ``JsonWriterSettings`` instance to specify options, +such as the Extended JSON format. By default, ``JsonWriter`` uses the Relaxed mode +format. The {+driver-short+}'s document classes also use this class to convert BSON +to Extended JSON. + +The following example uses a ``JsonWriter`` object to create +Canonical mode Extended JSON string values and output them to ``System.out``: + +.. io-code-block:: + :copyable: + + .. input:: /includes/data-formats/ext-json.kt + :language: kotlin + :start-after: start-write-bson + :end-before: end-write-bson + :dedent: + + .. output:: + :visible: false + + {"_id": {"$oid": "507f1f77bcf86cd799439012"}, "myNumber": {"$numberLong": "11223344"}} + +Custom BSON Type Conversion +--------------------------- + +In addition to specifying the Extended JSON output format, you +can further customize the output by adding converters to your +``JsonWriterSettings`` object. These converter methods specify logic +for handling different data types during the conversion process. + +The following example converts the same document as the :ref:`kotlin-sync-write-ejson-doc` +example. However, this example defines the ``objectIdConverter()`` and ``dateTimeConverter()`` +converter methods in a ``JsonWriterSettings`` object to simplify the Relaxed mode +Extended JSON output: + +.. io-code-block:: + :copyable: + + .. input:: /includes/data-formats/ext-json.kt + :language: kotlin + :start-after: start-custom-conversion + :end-before: end-custom-conversion + :dedent: + + .. output:: + :visible: false + + {"_id": "507f1f77bcf86cd799439012", "createdAt": "2020-09-30T21:00:09Z", "myNumber": 4794261} + +API Documentation +----------------- + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- `Document <{+api-root+}/bson/org/bson/Document.html>`__ +- `Document.parse() <{+api-root+}/bson/org/bson/Document.html#parse(java.lang.String)>`__ +- `JsonReader <{+api-root+}/bson/org/bson/json/JsonReader.html>`__ +- `JsonWriter <{+api-root+}/bson/org/bson/json/JsonWriter.html>`__ +- `Document.toJson() <{+api-root+}/bson/org/bson/Document.html#toJson()>`__ +- `JsonWriterSettings <{+api-root+}/bson/org/bson/json/JsonWriterSettings.html>`__ \ No newline at end of file diff --git a/source/includes/data-formats/ext-json.kt b/source/includes/data-formats/ext-json.kt new file mode 100644 index 00000000..fe48d7ab --- /dev/null +++ b/source/includes/data-formats/ext-json.kt @@ -0,0 +1,105 @@ +package org.example + +import org.bson.json.JsonWriter +import org.bson.json.JsonWriterSettings +import java.util.Date +import org.bson.Document +import org.bson.json.JsonMode +import org.bson.json.JsonReader +import org.bson.types.ObjectId +import java.time.Instant +import java.time.ZoneOffset +import java.time.format.DateTimeFormatter +import java.io.BufferedWriter +import java.io.OutputStreamWriter + +fun main() { + + // start-read-doc + val ejsonStr = """ + { + "_id": { "$${"oid"}": "507f1f77bcf86cd799439011" }, + "myNumber": { "$${"numberLong"}": "4794261" } + } + """.trimIndent() + + val doc = Document.parse(ejsonStr) + println(doc) + // end-read-doc + + // start-read-bson + val string = """ + { + "_id": { "$${"oid"}": "507f1f77bcf86cd799439011" }, + "myNumber": { "$${"numberLong"}": "4794261" } + } + """.trimIndent() + + val jsonReader = JsonReader(string) + jsonReader.readStartDocument() + + // Reads the "_id" field value + jsonReader.readName("_id") + val id = jsonReader.readObjectId() + + // Reads the "myNumber" field value + jsonReader.readName("myNumber") + val myNumber = jsonReader.readInt64() + + jsonReader.readEndDocument() + + println("$id is type: ${id::class.qualifiedName}") + println("$myNumber is type: ${myNumber::class.qualifiedName}") + + jsonReader.close() + // end-read-bson + + // start-write-doc + val doc = Document() + .append("_id", ObjectId("507f1f77bcf86cd799439012")) + .append("createdAt", Date.from(Instant.ofEpochMilli(1601499609000L))) + .append("myNumber", 4794261) + + val settings = JsonWriterSettings.builder() + .outputMode(JsonMode.RELAXED) + .build() + + println(doc.toJson(settings)) + // end-write-doc + + // start-write-bson + val settings = JsonWriterSettings.builder() + .outputMode(JsonMode.EXTENDED) + .build() + + JsonWriter(BufferedWriter(OutputStreamWriter(System.out)), settings).use { jsonWriter -> + jsonWriter.writeStartDocument() + jsonWriter.writeName("_id") + jsonWriter.writeObjectId(ObjectId("507f1f77bcf86cd799439012")) + jsonWriter.writeName("myNumber") + jsonWriter.writeInt64(11223344L) + jsonWriter.writeEndDocument() + jsonWriter.flush() + } + // end-write-bson + + // start-custom-conversion + val settings = JsonWriterSettings.builder() + .outputMode(JsonMode.RELAXED) + .objectIdConverter { value, writer -> + writer.writeString(value.toHexString()) + } + .dateTimeConverter { value, writer -> + val zonedDateTime = Instant.ofEpochMilli(value).atZone(ZoneOffset.UTC) + writer.writeString(DateTimeFormatter.ISO_DATE_TIME.format(zonedDateTime)) + } + .build() + + val doc = Document() + .append("_id", ObjectId("507f1f77bcf86cd799439012")) + .append("createdAt", Date.from(Instant.ofEpochMilli(1601499609000L))) + .append("myNumber", 4794261) + + println(doc.toJson(settings)) + // end-custom-conversion +} \ No newline at end of file From 6f62210e234cc9ee28e60a127496068b356e3c49 Mon Sep 17 00:00:00 2001 From: Michael Morisi Date: Thu, 17 Jul 2025 09:34:38 -0400 Subject: [PATCH 09/22] DOCSP-51324: Network Compression (#110) --- source/connect.txt | 28 ------ source/connect/connection-options.txt | 8 +- .../connect/{ => connection-options}/csot.txt | 0 .../network-compression.txt | 96 +++++++++++++++++++ .../{ => connection-options}/stable-api.txt | 0 5 files changed, 99 insertions(+), 33 deletions(-) rename source/connect/{ => connection-options}/csot.txt (100%) create mode 100644 source/connect/connection-options/network-compression.txt rename source/connect/{ => connection-options}/stable-api.txt (100%) diff --git a/source/connect.txt b/source/connect.txt index ca6d1a99..999d8848 100644 --- a/source/connect.txt +++ b/source/connect.txt @@ -121,34 +121,6 @@ connecting by using TLS: .. To learn more about disabling hostname verification, see :ref:`kotlin-sync-insecure-tls` in .. the TLS configuration guide. -Network Compression -------------------- - -The following sections describe how to connect to MongoDB -while specifying network compression algorithms. - -Compression Algorithms -~~~~~~~~~~~~~~~~~~~~~~ - -The following tabs demonstrate how to specify all available compressors -while connecting to MongoDB: - -.. include:: /includes/connect/compression-tabs.rst - -.. To learn more about specifying compression algorithms, see -.. :ref:`kotlin-sync-enable-compression` in the Network Compression guide. - -zlib Compression Level -~~~~~~~~~~~~~~~~~~~~~~ - -The following tabs demonstrate how to specify a compression level for -the ``zlib`` compressor: - -.. include:: /includes/connect/zlib-level-tabs.rst - -.. To learn more about setting the zlib compression level, see -.. :ref:`kotlin-sync-enable-compression` in the Network Compression guide. - Server Selection ---------------- diff --git a/source/connect/connection-options.txt b/source/connect/connection-options.txt index f01765be..16be34bc 100644 --- a/source/connect/connection-options.txt +++ b/source/connect/connection-options.txt @@ -15,13 +15,11 @@ Specify Connection Options :titlesonly: :maxdepth: 1 - Stable API - Limit Server Execution Time + Network Compression + Stable API + Limit Server Execution Time Connection Pools -.. /connect/network-compression -.. /connect/server-selection - Overview -------- diff --git a/source/connect/csot.txt b/source/connect/connection-options/csot.txt similarity index 100% rename from source/connect/csot.txt rename to source/connect/connection-options/csot.txt diff --git a/source/connect/connection-options/network-compression.txt b/source/connect/connection-options/network-compression.txt new file mode 100644 index 00000000..4387b9be --- /dev/null +++ b/source/connect/connection-options/network-compression.txt @@ -0,0 +1,96 @@ +.. _kotlin-sync-compression: + +======================== +Compress Network Traffic +======================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: zlib, zstandard, zstd, snappy + +Overview +-------- + +In this guide, you can learn how to use the {+driver-short+} to enable network +compression. The driver provides a connection option to compress messages, which +reduces the amount of data passed over the network between MongoDB and your application. + +The driver supports the following compression algorithms: + +- `Snappy `__ +- `Zlib `__ +- `Zstandard `__ + +If you specify multiple compression algorithms, the driver selects the first one +in the list supported by your MongoDB instance. + +.. note:: + + Applications that require Snappy or Zstandard compression must + add explicit dependencies for those algorithms. To learn more, + see the :ref:`kotlin-sync-compression-dependencies` section of this guide. + +Specify Compression Algorithms +------------------------------ + +You can enable compression for the connection to your MongoDB instance +by specifying the algorithms in one of the following ways: + +- Chain the ``compressorList()`` method to the ``MongoClientSettings.builder()`` method. +- Use the ``compressors`` parameter in your connection URI. + +The following examples demonstrate how to specify all available compressors +while connecting to MongoDB. Select the :guilabel:`MongoClientSettings` or :guilabel:`Connection URI` +tab to see the corresponding syntax: + +.. include:: /includes/connect/compression-tabs.rst + +Specify the Zlib Compression Level +---------------------------------- + +If you specify ``zlib`` as one of your compression algorithms, you can also use the +``MongoCompressor.LEVEL`` property to specify a compression level. This option accepts +an integer value between ``-1`` and ``9``: + +- **-1:** Default compression (usually ``6``) +- **0:** No compression +- **1:** Fastest speed but lowest compression +- **9:** Best compression but slowest speed + +The following examples demonstrate how to specify a compression level for +the ``zlib`` compressor. Select the :guilabel:`MongoClientSettings` or :guilabel:`Connection URI` +tab to see the corresponding syntax: + +.. include:: /includes/connect/zlib-level-tabs.rst + +.. _kotlin-sync-compression-dependencies: + +Compression Algorithm Dependencies +---------------------------------- + +The JDK natively supports `Zlib `__ compression. However, +Snappy and Zstandard depend on open source Java implementations. To learn more +about these implementations, see the following GitHub repositories: + +- `snappy-java `__ +- `zstd-jni `__ + +API Documentation +----------------- + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- `MongoClient <{+driver-api+}/-mongo-client/index.html>`__ +- `createSnappyCompressor() <{+core-api+}/MongoCompressor.html#createSnappyCompressor()>`__ +- `createZlibCompressor() <{+core-api+}/MongoCompressor.html#createZlibCompressor()>`__ +- `createZstdCompressor() <{+core-api+}/MongoCompressor.html#createZstdCompressor()>`__ \ No newline at end of file diff --git a/source/connect/stable-api.txt b/source/connect/connection-options/stable-api.txt similarity index 100% rename from source/connect/stable-api.txt rename to source/connect/connection-options/stable-api.txt From c8b17c10d9b355f41fdee5297216020f9b99aa02 Mon Sep 17 00:00:00 2001 From: Nora Reidy Date: Thu, 17 Jul 2025 16:15:38 -0400 Subject: [PATCH 10/22] DOCSP-51350: Vector search queries (#117) * DOCSP-51350: Vector search queries * edit * NX feedback * edits * word --- source/atlas-vector-search.txt | 132 ++++++++++++++++++++++++++++++- source/includes/vector-search.kt | 84 ++++++++++++++++++++ 2 files changed, 215 insertions(+), 1 deletion(-) create mode 100644 source/includes/vector-search.kt diff --git a/source/atlas-vector-search.txt b/source/atlas-vector-search.txt index cf6585fe..adc1e42b 100644 --- a/source/atlas-vector-search.txt +++ b/source/atlas-vector-search.txt @@ -2,4 +2,134 @@ ================================ Run an Atlas Vector Search Query -================================ \ No newline at end of file +================================ + +.. 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-short+}. + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +In this guide, you can learn how to use the {+driver-short+} to perform +:atlas:`Atlas Vector Search ` +queries. The ``Aggregates`` builders class provides the +``vectorSearch()`` helper method, which you can use to +create a :atlas:`$vectorSearch ` +pipeline stage. + +.. important:: Feature Compatibility + + To learn which versions of MongoDB Atlas support this feature, see + :atlas:`Limitations ` + in the MongoDB Atlas documentation. + +Perform a Vector Search +----------------------- + +Before you can perform Atlas Vector Search queries, you must create an Atlas Vector Search +index on your collection. To learn how to programmatically create a +vector search index, see the :ref:`kotlin-sync-search-avs-indexes` guide. + +Then, you can run an Atlas Vector Search query by using the +``vectorSearch()`` method in an aggregation pipeline. This +method accepts the following parameters: + +- ``path``: The field to search +- ``queryVector``: The vector embedding that represents your search query +- ``indexName``: The name of the Atlas Vector Search index to use +- ``limit``: The maximum number of results to return +- ``options``: *(Optional)* A set of options that you can use to configure the + vector search query + +Basic Vector Search Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This example runs an Atlas Vector Search query that performs +the following actions: + +- Queries the ``plot_embedding`` vector field. +- Limits the results to ``5`` documents. +- Specifies an Approximate Nearest Neighbor (ANN) vector search that considers + ``150`` candidates. To learn more about ANN searches, see :atlas:`ANN Search ` + in the MongoDB Atlas documentation. + +.. io-code-block:: + + .. input:: /includes/vector-search.kt + :start-after: start-vs + :end-before: end-vs + :language: kotlin + :dedent: + + .. output:: + :visible: false + + {"title": "Berserk: The Golden Age Arc I - The Egg of the King"} + {"title": "Rollerball"} + {"title": "After Life"} + {"title": "What Women Want"} + {"title": "Truth About Demons"} + +.. 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. + +Vector Search Score Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example shows how to run same vector search +query as the preceding example and print the documents' vector search +meta-score. This score represents the relevance of each +document to the query vector: + +.. io-code-block:: + + .. input:: /includes/vector-search.kt + :start-after: start-vs-score + :end-before: end-vs-score + :language: kotlin + :dedent: + + .. output:: + :visible: false + + Title: Berserk: The Golden Age Arc I - The Egg of the King, Score: 0.49899211525917053 + Title: Rollerball, Score: 0.4976102113723755 + Title: After Life, Score: 0.4965665936470032 + Title: What Women Want, Score: 0.49622756242752075 + Title: Truth About Demons, Score: 0.49614521861076355 + +.. tip:: Vector Search Tutorials + + To view more tutorials that show how to run Atlas Vector Search queries, + see the :atlas:`Atlas Vector Search Tutorials ` + in the MongoDB Atlas documentation. + +API Documentation +----------------- + +To learn more about the methods and types mentioned in this +guide, see the following API documentation: + +- `Aggregates.vectorSearch() + <{+core-api+}/client/model/Aggregates.html#vectorSearch(com.mongodb.client.model.search.FieldSearchPath,java.lang.Iterable,java.lang.String,long,com.mongodb.client.model.search.VectorSearchOptions)>`__ + +- `VectorSearchOptions + <{+core-api+}/client/model/search/VectorSearchOptions.html>`__ + +- `Projections.metaVectorSearchScore() + <{+core-api+}/client/model/Projections.html#metaVectorSearchScore(java.lang.String)>`__ diff --git a/source/includes/vector-search.kt b/source/includes/vector-search.kt new file mode 100644 index 00000000..78036153 --- /dev/null +++ b/source/includes/vector-search.kt @@ -0,0 +1,84 @@ +package org.example + +import com.mongodb.ConnectionString +import com.mongodb.kotlin.client.MongoClient +import com.mongodb.MongoClientSettings +import com.mongodb.client.model.Aggregates.project +import com.mongodb.client.model.Aggregates.vectorSearch +import com.mongodb.client.model.search.FieldSearchPath +import com.mongodb.client.model.Projections +import com.mongodb.client.model.search.SearchPath.fieldPath +import org.bson.BinaryVector +import org.bson.conversions.Bson +import com.mongodb.client.model.search.VectorSearchOptions.approximateVectorSearchOptions +import org.bson.Document + +fun main() { + val uri = "" + + val settings = MongoClientSettings.builder() + .applyConnectionString(ConnectionString(uri)) + .retryWrites(true) + .build() + + val mongoClient = MongoClient.create(settings) + val database = mongoClient.getDatabase("sample_mflix") + val collection = database.getCollection("embedded_movies") + + // start-vs + val vectorValues = FloatArray(1536) { i -> (i % 10).toFloat() * 0.1f } + val queryVector = BinaryVector.floatVector(vectorValues) + val indexName = "" + + // Specifies the path of the field to search + val fieldSearchPath: FieldSearchPath = fieldPath("plot_embedding") + + // Creates the vector search pipeline stage with a limit and numCandidates + val pipeline: List = listOf( + vectorSearch( + fieldSearchPath, + queryVector, + indexName, + 5L, + approximateVectorSearchOptions(150) + ), + project( + Projections.fields( + Projections.excludeId(), + Projections.include("title") + ) + ) + ) + + val results = collection.aggregate(pipeline) + + results.forEach { doc -> + println(doc.toJson()) + } + // end-vs + + // start-vs-score + val pipeline: List = listOf( + vectorSearch( + fieldSearchPath, + queryVector, + indexName, + 5L, + approximateVectorSearchOptions(150) + ), + project( + Projections.fields( + Projections.excludeId(), + Projections.include("title"), + Projections.metaVectorSearchScore("score") + ) + ) + ) + + val results = collection.aggregate(pipeline) + + results.forEach { doc -> + println("Title: ${doc.getString("title")}, Score: ${doc.getDouble("score")}") + } + // end-vs-score +} From 4d6d754c0c8d0e6d08a2e70ba2986353b20fa47d Mon Sep 17 00:00:00 2001 From: Nora Reidy Date: Mon, 21 Jul 2025 15:40:26 -0400 Subject: [PATCH 11/22] DOCSP-51321: Configure CRUD operations (#113) * DOCSP-51321: Configure CRUD operations * keywords * MW feedback --- source/crud/configure.txt | 331 +++++++++++++++++++++++++++++- source/includes/configure-crud.kt | 111 ++++++++++ 2 files changed, 441 insertions(+), 1 deletion(-) create mode 100644 source/includes/configure-crud.kt diff --git a/source/crud/configure.txt b/source/crud/configure.txt index f2e20e7b..175dd382 100644 --- a/source/crud/configure.txt +++ b/source/crud/configure.txt @@ -8,4 +8,333 @@ Configure CRUD Operations :local: :backlinks: none :depth: 2 - :class: singlecol \ No newline at end of file + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: customize, preferences, replica set, consistency, kotlin + +Overview +-------- + +In this guide, you can learn how to configure **write concern**, **read concern**, +and **read preference** options to modify the way that the {+driver-short+} runs +read and write operations on replica sets. + +Read and Write Settings Precedence +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can set write concern, read concern, and read preference options at the following +levels: + +- Client, which sets the *default for all operation executions* unless overridden +- Transaction +- Database +- Collection + +This list also indicates the increasing order of precedence of the option settings. For +example, if you set a read concern for a transaction, it will override the read +concern settings inherited from the client. + +Write concern, read concern, and read preference options allow you to customize the +causal consistency and availability of the data in your replica sets. To see a full +list of these options, see the following guides in the {+mdb-server+} manual: + +- :manual:`Read Preference ` +- :manual:`Read Concern ` +- :manual:`Write Concern ` + +.. _kotlin-sync-read-write-config: + +Configure Read and Write Operations +----------------------------------- + +You can control how the driver routes read operations among replica set members +by setting a read preference. You can also control how the driver waits for +acknowledgment of read and write operations on a replica set by setting read and +write concerns. + +The following sections show how to configure these read and write settings +at various levels. + +.. _kotlin-sync-read-write-client: + +Client Configuration +~~~~~~~~~~~~~~~~~~~~ + +This example shows how to set the read preference, read concern, and +write concern of a ``MongoClient`` instance by passing a ``MongoClientSettings`` +instance to the ``MongoClient.create()`` method. The code configures the +following settings: + +- ``secondary`` read preference: Read operations retrieve data from + secondary replica set members. +- ``LOCAL`` read concern: Read operations return the instance's most recent data + without guaranteeing that the data has been written to a majority of the replica + set members. +- ``W2`` write concern: The primary replica set member and one secondary member + must acknowledge the write operation. + +.. literalinclude:: /includes/configure-crud.kt + :language: kotlin + :dedent: + :start-after: start-client-settings + :end-before: end-client-settings + +Alternatively, you can specify the read and write settings in the connection +URI, which is passed as a parameter to the ``MongoClient.create()`` method: + +.. literalinclude:: /includes/configure-crud.kt + :language: kotlin + :dedent: + :start-after: start-client-settings-uri + :end-before: end-client-settings-uri + +.. _kotlin-sync-read-write-transaction: + +Transaction Configuration +~~~~~~~~~~~~~~~~~~~~~~~~~ + +This example shows how to set the read preference, read concern, and +write concern of a transaction by passing a ``TransactionOptions`` +instance to the ``withTransaction()`` method. Transactions run within +**sessions**, which are groupings of related read or write operations that you +intend to run sequentially. Before applying the transaction options, use the +``startSession()`` method to start a session. + +.. tip:: + + To learn more about sessions, see :manual:`Server Sessions ` + in the {+mdb-server+} manual. + +The example configures the following settings: + +- ``primary`` read preference: Read operations retrieve data from + the primary replica set member. +- ``MAJORITY`` read concern: Read operations return the instance's most recent data + that has been written to a majority of replica set members. +- ``W1`` write concern: The primary replica set member must acknowledge the + write operation. + +.. literalinclude:: /includes/configure-crud.kt + :language: kotlin + :dedent: + :start-after: start-transaction-settings + :end-before: end-transaction-settings + +.. _kotlin-sync-read-write-database: + +Database Configuration +~~~~~~~~~~~~~~~~~~~~~~ + +This example shows how to set the read preference, read concern, and +write concern of a database called ``test_database`` by chaining setter +methods to the ``getDatabase()`` method. The code configures the following +settings: + +- ``primaryPreferred`` read preference: Read operations retrieve data from + the primary replica set member, or secondary members if the primary is unavailable. +- ``AVAILABLE`` read concern: Read operations return the instance's most recent data + without guaranteeing that the data has been written to a majority of the replica + set members. +- ``MAJORITY`` write concern: The majority of all replica set members + must acknowledge the write operation. + +.. literalinclude:: /includes/configure-crud.kt + :language: kotlin + :dedent: + :start-after: start-database-settings + :end-before: end-database-settings + +.. _kotlin-sync-read-write-collection: + +Collection Configuration +~~~~~~~~~~~~~~~~~~~~~~~~ + +This example shows how to set the read preference, read concern, and +write concern of a collection called ``test_collection`` by chaining setter +methods to the ``getCollection()`` method. The code configures the following +settings: + +- ``secondaryPreferred`` read preference: Read operations retrieve data from + secondary replica set members, or the primary members if no secondary members are + available. +- ``AVAILABLE`` read concern: Read operations return the instance's most recent data + without guaranteeing that the data has been written to a majority of the replica + set members. +- ``UNACKNOWLEDGED`` write concern: Replica set members do not need to acknowledge + the write operation. + +.. literalinclude:: /includes/configure-crud.kt + :language: kotlin + :dedent: + :start-after: start-collection-settings + :end-before: end-collection-settings + +.. _kotlin-sync-read-write-advanced: + +Advanced Read Configurations +---------------------------- + +The following sections describe ways to further customize how the {+driver-short+} +routes read operations. + +.. _kotlin-sync-sharded-clusters: + +Sharded Clusters +~~~~~~~~~~~~~~~~ + +You can specify a read preference when connecting to a sharded cluster. +MongoDB uses sharding to divide datasets by key ranges and distribute data across multiple +database instances. A sharded cluster, or the set of nodes in a sharded deployment, +includes the following components: + +- **Shard**: A replica set that contains a subset of the sharded data. +- **Mongos**: A query router that provides an interface between your + application and the sharded cluster. +- **Config servers**: Servers that store the cluster's configuration settings + and metadata. + +.. tip:: + + To learn more about sharded clusters, see :manual:`Sharding ` + in the {+mdb-server+} manual. + +When reading from the replica set shards, ``mongos`` applies your specified read +preference. The read preference is re-evaluated for each operation. + +The following example shows how to connect to a sharded cluster and specify a +``secondary`` read preference in your connection string: + +.. literalinclude:: /includes/configure-crud.kt + :language: kotlin + :dedent: + :start-after: start-sharded-cluster-uri + :end-before: end-sharded-cluster-uri + +.. _kotlin-sync-tag-sets: + +Tag Sets +~~~~~~~~ + +In {+mdb-server+}, you can apply key-value :manual:`tags +` to replica set members +according to any criteria you choose. You can then use those +tags to target one or more members for a read operation. + +By default, the {+driver-short+} ignores tags when choosing a member +to read from. To instruct the {+driver-short+} to prefer certain tags, +pass the tags as a list to your read preference setter method. + +Suppose you are connected to a replica set that contains members hosted +at multiple data centers across the United States. You want the driver to +prefer reads from secondary replica set members in the following order: + +1. Members from the New York data center, tagged with ``("dc", "ny")`` +#. Members from the San Francisco data center, tagged with ``("dc", "sf")`` +#. Any secondary members + +This code example passes a list of tags representing the preceding replica +set members to the ``ReadPreference.secondary()`` setter method. Then, the code +passes the read preference information to the ``withReadPreference()`` method +to set the read order on the database: + +.. literalinclude:: /includes/configure-crud.kt + :language: kotlin + :dedent: + :start-after: start-tag-set + :end-before: end-tag-set + +Load Balancing +~~~~~~~~~~~~~~ + +When connecting to a sharded cluster or a replica set, the {+driver-short+} uses +**load balancing** to handle read and write requests. Load balancing allows the driver to +distribute these requests across multiple servers, which avoids overwhelming +any one server and ensures optimal performance. + +When connecting to a sharded cluster, the {+driver-short+} determines the closest ``mongos`` +instance by calculating which one has the lowest network round-trip time. Then, the driver +determines the latency window by adding this ``mongos``'s average round-trip time to the +:ref:`localThresholdMS value `. The driver load balances requests +across up to two random ``mongos`` instances that fall within the latency window. For each request, +the driver chooses the server with the lower operation load by determining its ``operationCount`` +value. + +When connecting to a replica set, the {+driver-short+} first selects replica set members +according to your read preference. Then, the driver follows the same process as +described in the preceding paragraph. After calculating the latency window, the driver +selects up to two random replica set members that fall within the window and chooses +the member with the lower ``operationCount`` value to receive the request. + +.. tip:: + + To learn more about load balancing, see :manual:`Sharded Cluster Balancer + ` in the {+mdb-server+} manual. + +.. _kotlin-sync-local-threshold: + +Local Threshold +``````````````` + +The {+driver-short+} uses the local threshold value to calculate the +latency window for server selection. This value determines the servers +that are eligible to receive read and write requests. + +By default, the driver uses only ``mongos`` instances or replica set members whose +ping times are within 15 milliseconds of the nearest server. To +distribute reads among servers with higher latencies, set the ``localThreshold`` +option in a ``MongoClientSettings`` instance or the ``localThresholdMS`` option +in your connection URI. + +.. note:: + + When selecting replica set members from a single ``mongos`` instance, the + {+driver-short+} ignores the ``localThresholdMS`` option. In this case, use the + :manual:`localThreshold ` + command-line option. + +The following example connects to a replica set and specifies a local threshold +of 35 milliseconds. Select the :guilabel:`MongoClientSettings` or :guilabel:`Connection URI` +tab to see corresponding code for each approach: + +.. tabs:: + + .. tab:: MongoClientSettings + :tabid: settings + + .. literalinclude:: /includes/configure-crud.kt + :language: rust + :dedent: + :start-after: start-local-threshold-settings + :end-before: end-local-threshold-settings + + + .. tab:: Connection URI + :tabid: uri + + .. literalinclude:: /includes/configure-crud.kt + :language: rust + :dedent: + :start-after: start-local-threshold-uri + :end-before: end-local-threshold-uri + +In the preceding example, the {+driver-short+} distributes reads among matching members +within 35 milliseconds of the closest member's ping time. + +API Documentation +----------------- + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- `MongoClient <{+driver-api+}/-mongo-client/index.html>`__ +- `MongoClientSettings <{+core-api+}/MongoClientSettings.html>`__ +- `TransactionOptions <{+core-api+}/TransactionOptions.html>`_ +- `startTransaction() <{+driver-api+}/-client-session/start-transaction.html>`__ +- `MongoDatabase <{+driver-api+}/-mongo-database/index.html>`__ +- `MongoCollection <{+driver-api+}/-mongo-collection/index.html>`__ +- `TagSet <{+core-api+}/TagSet.html>`_ \ No newline at end of file diff --git a/source/includes/configure-crud.kt b/source/includes/configure-crud.kt new file mode 100644 index 00000000..3d5150dd --- /dev/null +++ b/source/includes/configure-crud.kt @@ -0,0 +1,111 @@ +import org.bson.Document +import com.mongodb.ConnectionString +import com.mongodb.MongoClientSettings +import com.mongodb.ReadConcern +import com.mongodb.ReadPreference +import com.mongodb.Tag +import com.mongodb.TagSet +import com.mongodb.TransactionOptions +import com.mongodb.WriteConcern +import com.mongodb.kotlin.client.MongoClient +import java.util.concurrent.TimeUnit + +fun main() { + // Uses the settings builder methods to set read and write settings for the client + // start-client-settings + val settings = MongoClientSettings.builder() + .applyConnectionString(ConnectionString("mongodb://localhost:27017/")) + .readPreference(ReadPreference.secondary()) + .readConcern(ReadConcern.LOCAL) + .writeConcern(WriteConcern.W2) + .build() + + val mongoClient = MongoClient.create(settings) + // end-client-settings + + // Uses connection URI parameters to set read and write settings for the client + // start-client-settings-uri + val uri = "mongodb://localhost:27017/?readPreference=secondary&w=2&readConcernLevel=local" + val uriClient = MongoClient.create(uri) + // end-client-settings-uri + + // Sets read and write settings for the transaction + // start-transaction-settings + mongoClient.startSession().use { session -> + try { + // Sets transaction read and write settings + val txnOptions = TransactionOptions.builder() + .readPreference(ReadPreference.primary()) + .readConcern(ReadConcern.MAJORITY) + .writeConcern(WriteConcern.W1) + .build() + + session.withTransaction({ + // Specify transaction operations here + }, txnOptions) + } catch (e: Exception) { + println("Transaction failed: ${e.message}") + } + } + // end-transaction-settings + + // Sets read and write settings for the "test_database" database + // start-database-settings + val database = mongoClient.getDatabase("test_database") + .withReadPreference(ReadPreference.primaryPreferred()) + .withReadConcern(ReadConcern.AVAILABLE) + .withWriteConcern(WriteConcern.MAJORITY) + // end-database-settings + + // Sets read and write settings for the "test_collection" collection + // start-collection-settings + val collection = database.getCollection("test_collection") + .withReadPreference(ReadPreference.secondaryPreferred()) + .withReadConcern(ReadConcern.AVAILABLE) + .withWriteConcern(WriteConcern.UNACKNOWLEDGED) + // end-collection-settings + + // Uses connection URI parameters to set a sharded cluster read preference + // start-sharded-cluster-uri + val shardedClient = MongoClient.create( + "mongodb://user:password@mongos1.example.com,mongos2.example.com/?readPreference=secondary" + ) + // end-sharded-cluster-uri + + // Instructs the driver to prefer reads from secondary replica set members + // located in New York, then San Francisco, then fallback to any secondary. + // start-tag-set + val tag1 = TagSet(Tag("dc", "ny")) + val tag2 = TagSet(Tag("dc", "sf")) + val tag3 = TagSet() // Empty tag set as fallback + + val readPref = ReadPreference.secondary(listOf(tag1, tag2, tag3)) + + val taggedDb = mongoClient.getDatabase("test_database") + .withReadPreference(readPref) + // end-tag-set + + // Instructs the library to distribute reads between members within 35 milliseconds + // of the closest member's ping time using client settings + // start-local-threshold-uri + val latencyClient1 = MongoClient.create( + "mongodb://localhost:27017/?replicaSet=repl0&localThresholdMS=35" + ) + // end-local-threshold-uri + + // Instructs the library to distribute reads between members within 35 milliseconds + // of the closest member's ping time using a URI option + // start-local-threshold-settings + val latencySettings = MongoClientSettings.builder() + .applyConnectionString(ConnectionString("mongodb://localhost:27017/")) + .applyToClusterSettings { builder -> + builder.localThreshold(35, TimeUnit.MILLISECONDS) + } + .build() + + val latencyClient2 = MongoClient.create(latencySettings) + // end-local-threshold-settings + + // Close the MongoClient connection + mongoClient.close() +} From 4be94d70c8c3130cc9020540978f30b415d41916 Mon Sep 17 00:00:00 2001 From: shuangela Date: Tue, 22 Jul 2025 10:52:26 -0400 Subject: [PATCH 12/22] DOCSP-51327-add-upsert (#121) * change title * edit title size --- source/crud/update.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/crud/update.txt b/source/crud/update.txt index 4ab6dc7a..ef184828 100644 --- a/source/crud/update.txt +++ b/source/crud/update.txt @@ -156,8 +156,8 @@ configure an ``UpdateOptions`` instance: fields ` guide in the {+mdb-server+} manual for more information. -Modify Update Example -````````````````````` +Upsert Documents Example +~~~~~~~~~~~~~~~~~~~~~~~~ The following code uses the ``updateOne()`` method to match documents in which the ``name`` field value is ``"Sunrise Pizzeria"``. It then From db6738d3085d916fbedfd2e9bad3eef8052d491d Mon Sep 17 00:00:00 2001 From: Nora Reidy Date: Wed, 23 Jul 2025 16:26:52 -0400 Subject: [PATCH 13/22] DOCSP-51407: Auth reorganization (#120) * DOCSP-51407: Auth reorganization * edit * toc * titles * MW feedback * vale --- snooty.toml | 3 +- source/security/authentication.txt | 530 ++------------------- source/security/authentication/aws-iam.txt | 323 +++++++++++++ source/security/authentication/scram.txt | 189 ++++++++ source/security/authentication/x509.txt | 90 ++++ 5 files changed, 647 insertions(+), 488 deletions(-) create mode 100644 source/security/authentication/aws-iam.txt create mode 100644 source/security/authentication/scram.txt create mode 100644 source/security/authentication/x509.txt diff --git a/snooty.toml b/snooty.toml index 752e3cee..6dd53417 100644 --- a/snooty.toml +++ b/snooty.toml @@ -17,7 +17,8 @@ toc_landing_pages = [ "/connect/connection-options", "/logging-and-monitoring", "/databases-and-collections", - "/api" + "/api", + "/security/authentication" ] sharedinclude_root = "https://raw.githubusercontent.com/10gen/docs-shared/main/" diff --git a/source/security/authentication.txt b/source/security/authentication.txt index 1f8ae90f..78d0b8e9 100644 --- a/source/security/authentication.txt +++ b/source/security/authentication.txt @@ -17,493 +17,49 @@ Authentication Mechanisms .. meta:: :keywords: validate credentials, protocols, code example -Overview --------- - -In this guide, you can learn how to authenticate to a MongoDB Server by using -each **authentication mechanism** available in the {+driver-long+}. -Authentication is the process by which the driver proves its identity to the -server to ensure security. - -.. note:: Enterprise Authentication Mechanisms - - This page describes the authentication mechanisms available in MongoDB - Community Edition. To authenticate with mechanisms available in - the MongoDB Enterprise Edition, like ``Kerberos`` or ``LDAP``, see the - :ref:`Enterprise Authentication Mechanisms guide `. - -.. _kotlin-sync-auth-default: -.. _kotlin-sync-auth-scramsha256: - -SCRAM-SHA-256 -------------- - -``SCRAM-SHA-256``, as defined by `RFC 7677 `__, -is a Salted Challenge Response Authentication Mechanism -(SCRAM) that uses your username and password, encrypted with the ``SHA-256`` -algorithm, to authenticate your user. This is the default authentication -mechanism. - -The following code snippets show how to specify this default authentication mechanism by -using the following placeholders: - -* ``db_username``: Your MongoDB database username. -* ``db_password``: Your MongoDB database user's password. -* ``hostname``: The network address of your MongoDB deployment, accessible by your client. -* ``port``: The port number of your MongoDB deployment. -* ``authenticationDb``: The MongoDB database that contains your user's - authentication data. If you omit this parameter, the driver uses the - default value ``admin``. - -Select the :guilabel:`Connection String` or the :guilabel:`MongoCredential` -tab below for instructions and sample code for specifying this authentication -mechanism: - -.. tabs:: - - .. tab:: - :tabid: Connection String - - To specify the default authentication mechanism by using a connection - string, omit the mechanism. Your code to instantiate a ``MongoClient`` - should resemble the following: - - .. literalinclude:: /includes/security/authentication.kt - :language: kotlin - :start-after: start-default-cred-string - :end-before: end-default-cred-string - :dedent: - - .. tab:: - :tabid: MongoCredential - - To specify the default authentication mechanism by using the - ``MongoCredential`` class, use the ``createCredential()`` method. - Your code to instantiate a ``MongoClient`` should resemble the following: - - .. literalinclude:: /includes/security/authentication.kt - :language: kotlin - :start-after: start-default-mongo-cred - :end-before: end-default-mongo-cred - :dedent: - -You can also explicitly specify the ``SCRAM-SHA-256`` authentication mechanism, -as shown in the following code snippets. - -Select the :guilabel:`Connection String` or the :guilabel:`MongoCredential` -tab below for instructions and sample code for specifying this authentication -mechanism: - -.. tabs:: - - .. tab:: - :tabid: Connection String - - To specify the ``SCRAM-SHA-256`` authentication mechanism by using a - connection string, assign the ``authMechanism`` parameter the value - ``SCRAM-SHA-256`` in your connection string. Your code to instantiate - a ``MongoClient`` should resemble the following: - - .. literalinclude:: /includes/security/authentication.kt - :language: kotlin - :dedent: - :start-after: start-scramsha256-cred-string - :end-before: end-scramsha256-cred-string - - .. tab:: - :tabid: MongoCredential - - To specify the default authentication mechanism by using the - ``MongoCredential`` class, use the - `createScramSha256Credential() <{+core-api+}/MongoCredential.html#createScramSha256Credential(java.lang.String,java.lang.String,char[])>`__ - method. Your code to instantiate a ``MongoClient`` should resemble the following: - - .. literalinclude:: /includes/security/authentication.kt - :language: kotlin - :dedent: - :start-after: start-scramsha256-mongo-cred - :end-before: end-scramsha256-mongo-cred - -.. _kotlin-sync-auth-scramsha1: - -SCRAM-SHA-1 ------------ - -``SCRAM-SHA-1``, as defined by `RFC 5802 `__, -is a Salted Challenge Response Authentication Mechanism (SCRAM) that uses your -username and password, encrypted with the ``SHA-1`` algorithm, to authenticate -your user. - -The following code snippets show how to specify the authentication mechanism -by using the following placeholders: - -* ``db_username``: Your MongoDB database username. -* ``db_password``: Your MongoDB database user's password. -* ``hostname``: The network address of your MongoDB deployment, accessible by your client. -* ``port``: The port number of your MongoDB deployment. -* ``authenticationDb``: The MongoDB database that contains your user's - authentication data. If you omit this parameter, the driver uses the - default value ``admin``. - -Select the :guilabel:`Connection String` or the :guilabel:`MongoCredential` -tab below for instructions and sample code for specifying this authentication -mechanism: - -.. tabs:: - - .. tab:: - :tabid: Connection String - - To specify the ``SCRAM-SHA-1`` authentication mechanism by using a - connection string, assign the ``authMechanism`` parameter the value - ``SCRAM-SHA-1`` in your connection string. Your code to instantiate - a ``MongoClient`` should resemble the following: - - .. literalinclude:: /includes/security/authentication.kt - :language: kotlin - :dedent: - :start-after: start-scramsha1-cred-string - :end-before: end-scramsha1-cred-string - - .. tab:: - :tabid: MongoCredential - - To specify the default authentication mechanism by using the - ``MongoCredential`` class, use the - `createScramSha1Credential() <{+core-api+}/MongoCredential.html#createScramSha1Credential(java.lang.String,java.lang.String,char[])>`__ - method. Your code to instantiate a ``MongoClient`` should resemble the following: - - .. literalinclude:: /includes/security/authentication.kt - :language: kotlin - :dedent: - :start-after: start-scramsha1-mongo-cred - :end-before: end-scramsha1-mongo-cred - -.. _kotlin-sync-auth-x509: - -MONGODB-X509 ------------- - -The ``MONGODB-X509`` authentication mechanism uses -:wikipedia:`TLS ` with X.509 certificates to -authenticate your user. When you specify the ``X.509`` -authentication mechanism, the server authenticates the connection by using -the subject name of the client certificate. - -The following code snippets show how to specify the authentication mechanism -by using the following placeholders: - -* ``hostname``: The network address of your MongoDB deployment, accessible by your client. -* ``port``: The port number of your MongoDB server. -* ``authenticationDb``: The MongoDB database that contains your user's - authentication data. If you omit this parameter, the driver uses the - default value ``admin``. - -Select the :guilabel:`Connection String` or the :guilabel:`MongoCredential` -tab below for instructions and sample code for specifying this authentication -mechanism: - -.. tabs:: - - .. tab:: - :tabid: Connection String - - To specify the ``X.509`` authentication mechanism by using a connection - string, assign the ``authMechanism`` parameter the value ``MONGODB-X509`` - and enable TLS by assigning the ``tls`` - parameter a ``true`` value. Your code to instantiate a ``MongoClient`` - should resemble the following: - - .. literalinclude:: /includes/security/authentication.kt - :language: kotlin - :dedent: - :start-after: start-x509-connect-string - :end-before: end-x509-connect-string - - .. tab:: - :tabid: MongoCredential - - To specify the ``X.509`` authentication mechanism by using the - ``MongoCredential`` class, use the - `createMongoX509Credential() <{+core-api+}/MongoCredential.html#createMongoX509Credential(java.lang.String)>`__ - method. Also, enable TLS by calling the - `applyToSslSettings() <{+core-api+}/MongoClientSettings.Builder.html#applyToSslSettings(com.mongodb.Block)>`__ - method and setting the ``enabled`` property to ``true`` in the - `SslSettings.Builder <{+core-api+}/connection/SslSettings.Builder.html>`__ - block. Your code to instantiate a ``MongoClient`` should resemble the following: - - .. literalinclude:: /includes/security/authentication.kt - :language: kotlin - :dedent: - :start-after: start-x509-mcred - :end-before: end-x509-mcred - -For additional information on configuring your application to use -certificates as well as TLS/SSL options, see the -:ref:`TLS/SSL guide `. - -.. _kotlin-sync-auth-aws: - -MONGODB-AWS ------------ - -.. note:: - - The MONGODB-AWS authentication mechanism is available for MongoDB - deployments on MongoDB Atlas. - -The ``MONGODB-AWS`` authentication mechanism uses your Amazon Web Services -Identity and Access Management (AWS IAM) credentials to authenticate your -user. To learn more about configuring MongoDB Atlas, see the -:atlas:`Set Up Authentication with AWS IAM ` -guide. - -To instruct the driver to use this authentication mechanism, you can either -specify ``MONGODB-AWS`` as a parameter in the connection string or call -the ``MongoCredential.createAwsCredential()`` factory method. - -In the following sections, you can learn different ways to specify the -``MONGODB-AWS`` authentication mechanism and provide your AWS IAM credentials. - -These sections contain code examples that use the following placeholders: - -* ``awsKeyId``: The value of your AWS access key ID -* ``awsSecretKey``: The value of your AWS secret access key -* ``atlasUri``: The network address of your MongoDB Atlas deployment -* ``hostname``: The hostname of your MongoDB Atlas deployment -* ``port``: The port of your MongoDB Atlas deployment -* ``awsSessionToken``: The value of your AWS session token +.. toctree:: + :caption: Authentication -.. _kotlin-mongodb-aws-sdk: + SCRAM + X.509 + AWS IAM -AWS SDK -~~~~~~~ - -.. note:: End of Support for AWS SDK for Java v1 - - The AWS SDK for Java v1 will reach end of support on December 31, 2025. - AWS recommends migrating to AWS SDK for Java v2. For more information, - see the `end of support announcement - `__ - on the AWS site. - -AWS provides software development kits (SDKs) for Java v1 and v2. -The AWS SDK offers the following features: - -- Multiple options for obtaining credentials -- Credential caching, which helps your application avoid rate limiting -- Credential provider management for use with the `Elastic Kubernetes Service `__ - -To use the AWS SDK for ``MONGODB-AWS`` authentication, you must -perform the following steps: - -1. Specify the authentication mechanism. -#. Add the SDK as a dependency to your project. -#. Supply your credentials by using one of the methods in the credential - provider chain. - -To specify the ``MONGODB-AWS`` authentication mechanism by using a ``MongoCredential`` -object, call the ``MongoCredential.createAwsCredential()`` factory method -and add the ``MongoCredential`` instance to your ``MongoClient``, as shown -in the following example: - -.. literalinclude:: /includes/security/authentication.kt - :language: kotlin - :dedent: - :start-after: start-aws-sdk-mcred - :end-before: end-aws-sdk-mcred - :emphasize-lines: 1, 9 - -To specify the ``MONGODB-AWS`` authentication mechanism in the connection string, -add it as a parameter, as shown in the following example: - -.. literalinclude:: /includes/security/authentication.kt - :language: kotlin - :dedent: - :start-after: start-aws-sdk-cred-string - :end-before: end-aws-sdk-cred-string - -To add the AWS SDK as a dependency to your project, see the following -AWS documentation for the version you need: - -- For the **AWS SDK for Java v2**, see the `Setting Up `__ - guide. -- For the **AWS SDK for Java v1**, see the `Getting Started `__ - guide. - -.. note:: - - For the AWS SDK for Java v2, the Java driver currently tests by using the - ``software.amazon.awssdk:auth:2.30.31`` dependency. - - For the AWS SDK for Java v1, the Java driver currently tests by using the - ``com.amazonaws:aws-java-sdk-core:1.12.782`` dependency. - -To supply your credentials, see the following AWS documentation for the -version you need: - -- To learn more about the **AWS SDK for Java v2** class the driver uses to - get the credentials, see the `DefaultCredentialsProvider `__ - API documentation. - - Learn how to supply your credentials to this class from the - `Use the default credential provider chain `__ - section. - -- To learn more about the **AWS SDK for Java v1** class the driver uses to - get the credentials, see the `DefaultAWSCredentialsProviderChain `__ - API documentation. - - Learn how to supply your credentials to this class from the - `Using the Default Credential Provider Chain `__ - section. - -.. note:: - - If you include both v1 and v2 of the AWS SDK for Java in your project, - you must use the v2 methods to supply your credentials. - -.. _kotlin-mongodb-aws-env-variables: - -Specify Your Credentials in the Environment -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can provide your AWS IAM credentials by instructing the driver to -use the ``MONGODB-AWS`` authentication mechanism and by setting the -appropriate environment variables. - -To use the environment variables to supply your credentials, you must perform -the following: - -1. Specify the authentication mechanism. -#. Add the appropriate environment variables. - -You can specify the ``MONGODB-AWS`` authentication mechanism by using a -``MongoCredential`` object or in the connection string. - -To specify the authentication mechanism by using a ``MongoCredential`` object, -call the ``MongoCredential.createAwsCredential()`` factory method and add the -``MongoCredential`` instance to your ``MongoClient``, as shown in the following -example: - -.. literalinclude:: /includes/security/authentication.kt - :language: kotlin - :dedent: - :start-after: start-aws-env-mcred - :end-before: end-aws-env-mcred - :emphasize-lines: 1, 9 - -To specify the ``MONGODB-AWS`` authentication mechanism in the connection -string, add it as a parameter as shown in the following example: - -.. literalinclude:: /includes/security/authentication.kt - :language: kotlin - :dedent: - :start-after: start-aws-env-cred-string - :end-before: end-aws-env-cred-string - -The next examples show how to provide your credentials by setting environment -variables for the following types of authentication: - -- Programmatic access keys -- ECS container credentials -- EC2 container credentials - -The following example shows how you can set your **programmatic access keys** -in environment variables by using ``bash`` or a similar shell: - -.. code-block:: bash - - export AWS_ACCESS_KEY_ID= - export AWS_SECRET_ACCESS_KEY= - export AWS_SESSION_TOKEN= - -Omit the line containing ``AWS_SESSION_TOKEN`` if you don't need an AWS -session token for that role. - -To authenticate by using **ECS container credentials**, set the ECS -endpoint relative URI in an environment variable by using ``bash`` or -a similar shell, as shown in the following example: - -.. code-block:: bash - - export AWS_CONTAINER_CREDENTIALS_RELATIVE_URI= - -To authenticate by using **EC2 container credentials**, make sure none of the -aforementioned environment variables are set. The driver obtains the -credentials from the default IPv4 EC2 instance metadata endpoint. - -.. _kotlin-mongodb-aws-mongoclient-configuration: - -Specify Your Credentials in a MongoCredential -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can supply your AWS IAM credentials to a ``MongoClient`` by using a -``MongoCredential`` instance. To construct the ``MongoCredential`` instance -for ``MONGODB-AWS`` authentication, call the -`createAwsCredential() <{+core-api+}/MongoCredential.html#createAwsCredential(java.lang.String,char%5B%5D)>`__ -factory method. - -You can supply only programmatic access keys to the -``MongoCredential.createAwsCredential()`` method. If you need to supply ECS -or EC2 container credentials, follow the instructions in -:ref:`` or :ref:``. - -To use a ``MongoCredential`` object for ``MONGODB-AWS`` authentication, you -must perform the following steps: - -1. Specify the authentication mechanism. -#. Supply the credentials. - -To specify the authentication mechanism by using a ``MongoCredential`` object, -call the ``MongoCredential.createAwsCredential()`` factory method -and add the ``MongoCredential`` instance to your ``MongoClient``, as shown -in the following example: - -.. literalinclude:: /includes/security/authentication.kt - :language: kotlin - :dedent: - :start-after: start-aws-mcred - :end-before: end-aws-mcred - :emphasize-lines: 1, 9 - -If you need to specify an AWS session token, pass it to the -`withMechanismProperty() <{+core-api+}/MongoCredential.html#withMechanismProperty(java.lang.String,T)>`__ -method, as shown in the following example: - -.. literalinclude:: /includes/security/authentication.kt - :language: kotlin - :dedent: - :start-after: start-aws-mcred-wmechprop - :end-before: end-aws-mcred-wmechprop - :emphasize-lines: 1, 2, 10 - -To refresh your credentials, you can declare a ``Supplier`` lambda expression -that returns new credentials, as shown in the following example: - -.. literalinclude:: /includes/security/authentication.kt - :language: kotlin - :dedent: - :start-after: start-aws-lambda-expression - :end-before: end-aws-lambda-expression - :emphasize-lines: 4-6, 9 - -If you must provide AWS IAM credentials in a connection string, you can add -it to your ``MongoClientSettings`` object by calling the `applyConnectionString() <{+core-api+}/MongoClientSettings.Builder.html#applyConnectionString(com.mongodb.ConnectionString)>`__ -method: - -.. literalinclude:: /includes/security/authentication.kt - :language: kotlin - :dedent: - :start-after: start-aws-apply-connect-string - :end-before: end-aws-apply-connect-string - :emphasize-lines: 2, 5 - -Additional Information ----------------------- - -To learn more about authenticating to MongoDB, see -:manual:`Authentication ` in the {+mdb-server+} manual. +Overview +-------- -To learn more about managing users of your MongoDB deployment, see -:manual:`Users ` in the {+mdb-server+} manual. +This guide describes the authentication mechanisms that the {+driver-short+} supports. +Authentication mechanisms are processes by which the driver and server confirm the +identity of a client to ensure security before connecting. + +.. tip:: Connect to MongoDB + + To learn how to connect to MongoDB by using the {+driver-short+}, see the + :ref:`kotlin-sync-mongoclient` guide. + +MongoDB Edition Compatibility +----------------------------- + +The following table lists the authentication mechanisms supported by MongoDB and +the {+mdb-server+} editions that each mechanism is compatible with. Click the name of +a mechanism to learn more about how to use it with your application. + +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + + * - Authentication Mechanism + - Atlas + - Enterprise Advanced + - Community + * - :ref:`` + - Yes + - Yes + - Yes + * - :ref:`` + - Yes + - Yes + - Yes + * - :ref:`` + - Yes + - No + - No diff --git a/source/security/authentication/aws-iam.txt b/source/security/authentication/aws-iam.txt new file mode 100644 index 00000000..88f6382e --- /dev/null +++ b/source/security/authentication/aws-iam.txt @@ -0,0 +1,323 @@ +.. _kotlin-sync-auth-aws: + +====================== +AWS IAM Authentication +====================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: atlas, amazon web services, code example + +Overview +-------- + +The **MONGODB-AWS** authentication mechanism uses Amazon Web Services +Identity and Access Management (AWS IAM) credentials to authenticate a user to MongoDB. +You can use this mechanism only when authenticating to MongoDB Atlas. + +.. tip:: Configure Atlas for AWS IAM Authentication + + To learn more about configuring MongoDB Atlas for AWS IAM authentication, see + :atlas:`Set Up Authentication with AWS IAM ` in + the Atlas documentation. + +Specify MONGODB-AWS Authentication +---------------------------------- + +To instruct the {+driver-short+} to use the ``MONGODB-AWS`` authentication mechanism, +you can either specify ``MONGODB-AWS`` as a parameter in the connection string or call +the ``MongoCredential.createAwsCredential()`` factory method. + +In the following sections, you can learn different ways to specify the +``MONGODB-AWS`` authentication mechanism and provide your AWS IAM credentials. + +These sections contain code examples that use the following placeholders: + +- ``awsKeyId``: The value of your AWS access key ID +- ``awsSecretKey``: The value of your AWS secret access key +- ``atlasUri``: The network address of your MongoDB Atlas deployment +- ``hostname``: The hostname of your MongoDB Atlas deployment +- ``port``: The port of your MongoDB Atlas deployment +- ``awsSessionToken``: The value of your AWS session token + +.. _kotlin-mongodb-aws-sdk: + +AWS SDK +~~~~~~~ + +.. note:: End of Support for AWS SDK for Java v1 + + The AWS SDK for Java v1 will reach end of support on December 31, 2025. + AWS recommends migrating to AWS SDK for Java v2. For more information, + see the `end of support announcement + `__ + on the AWS site. + +AWS provides software development kits (SDKs) for Java v1 and v2. +The AWS SDK offers the following features: + +- Multiple options for obtaining credentials +- Credential caching, which helps your application avoid rate limiting +- Credential provider management for use with the `Elastic Kubernetes Service `__ + +To use the AWS SDK for ``MONGODB-AWS`` authentication, perform +the following steps: + +1. :ref:`Specify the authentication mechanism `. +#. :ref:`Add the SDK as a dependency to your project `. +#. :ref:`Supply your credentials by using one of the methods in the credential provider chain `. + +.. _kotlin-mongodb-aws-sdk-specify: + +Specify the Authentication Mechanism +```````````````````````````````````` + +You can specify the ``MONGODB-AWS`` authentication mechanism by using a connection +string or a ``MongoCredential`` object. Select the :guilabel:`Connection String` +or the :guilabel:`MongoCredential` tab below for corresponding instructions and sample code: + +.. tabs:: + + .. tab:: + :tabid: Connection String + + To specify the ``MONGODB-AWS`` authentication mechanism in the connection string, + set the ``authMechanism`` parameter to ``MONGODB-AWS``, as shown in the following + example: + + .. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-aws-sdk-cred-string + :end-before: end-aws-sdk-cred-string + + .. tab:: + :tabid: MongoCredential + + To specify the ``MONGODB-AWS`` authentication mechanism by using a ``MongoCredential`` + object, call the ``MongoCredential.createAwsCredential()`` factory method + and add the ``MongoCredential`` instance to your ``MongoClient``, as shown + in the following example: + + .. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-aws-sdk-mcred + :end-before: end-aws-sdk-mcred + :emphasize-lines: 1, 9 + +.. _kotlin-mongodb-aws-sdk-dependency: + +Add the AWS SDK Dependency +`````````````````````````` + +To add the AWS SDK as a dependency to your project, see the following +AWS documentation for the version you need: + +- For the **AWS SDK for Java v2**, see the `Setting Up `__ + guide. +- For the **AWS SDK for Java v1**, see the `Getting Started `__ + guide. + +.. note:: + + For the AWS SDK for Java v2, the Java driver tests by using the + ``software.amazon.awssdk:auth:2.30.31`` dependency. + + For the AWS SDK for Java v1, the Java driver tests by using the + ``com.amazonaws:aws-java-sdk-core:1.12.782`` dependency. + +.. _kotlin-mongodb-aws-sdk-credentials: + +Supply Your Credentials +``````````````````````` + +To supply your credentials, see the following AWS documentation for the +version you need: + +- To learn more about the **AWS SDK for Java v2** class the driver uses to + get the credentials, see the `DefaultCredentialsProvider `__ + API documentation. + + Learn how to supply your credentials to this class from the + `Use the default credential provider chain `__ + section. + +- To learn more about the **AWS SDK for Java v1** class the driver uses to + get the credentials, see the `DefaultAWSCredentialsProviderChain `__ + API documentation. + + Learn how to supply your credentials to this class from the + `Using the Default Credential Provider Chain `__ + section. + +.. note:: + + If you include both v1 and v2 of the AWS SDK for Java in your project, + you must use the v2 methods to supply your credentials. + +.. _kotlin-mongodb-aws-env-variables: + +Specify Your Credentials in the Environment +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can provide your AWS IAM credentials by instructing the driver to +use the ``MONGODB-AWS`` authentication mechanism and by setting the +appropriate environment variables. + +To use the environment variables to supply your credentials, perform +the following steps: + +1. :ref:`Specify the authentication mechanism `. +#. :ref:`Add the appropriate environment variables `. + +.. _kotlin-mongodb-aws-env-specify: + +Specify the Authentication Mechanism +```````````````````````````````````` + +You can specify the ``MONGODB-AWS`` authentication mechanism by using a +``MongoCredential`` object or in the connection string. + +To specify the authentication mechanism by using a ``MongoCredential`` object, +call the ``MongoCredential.createAwsCredential()`` factory method and add the +``MongoCredential`` instance to your ``MongoClient``, as shown in the following +example: + +.. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-aws-env-mcred + :end-before: end-aws-env-mcred + :emphasize-lines: 1, 9 + +To specify the ``MONGODB-AWS`` authentication mechanism in the connection +string, add it as a parameter as shown in the following example: + +.. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-aws-env-cred-string + :end-before: end-aws-env-cred-string + +.. _kotlin-mongodb-aws-env-set-vars: + +Set Environment Variables +````````````````````````` + +This section shows how to provide your credentials by setting environment +variables for the following types of authentication: + +- Programmatic access keys +- ECS container credentials +- EC2 container credentials + +The following example shows how you can set your **programmatic access keys** +in environment variables by using ``bash`` or a similar shell: + +.. code-block:: bash + + export AWS_ACCESS_KEY_ID= + export AWS_SECRET_ACCESS_KEY= + export AWS_SESSION_TOKEN= + +Omit the line that sets the ``AWS_SESSION_TOKEN`` variable if you don't need an AWS +session token for that role. + +To authenticate by using **ECS container credentials**, set the ECS +endpoint relative URI in an environment variable by using ``bash`` or +a similar shell, as shown in the following example: + +.. code-block:: bash + + export AWS_CONTAINER_CREDENTIALS_RELATIVE_URI= + +To authenticate by using **EC2 container credentials**, do not set +the AWS environment variables. The driver obtains the credentials +from the default IPv4 EC2 instance metadata endpoint. + +.. _kotlin-mongodb-aws-mongoclient-configuration: + +Specify Your Credentials in a MongoCredential +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can supply your AWS IAM credentials to a ``MongoClient`` by using a +``MongoCredential`` instance. To construct the ``MongoCredential`` instance +for ``MONGODB-AWS`` authentication, call the +`createAwsCredential() <{+core-api+}/MongoCredential.html#createAwsCredential(java.lang.String,char%5B%5D)>`__ +factory method. + +.. tip:: + + You can supply only programmatic access keys to the + ``MongoCredential.createAwsCredential()`` method. If you must supply ECS + or EC2 container credentials, follow the instructions in + :ref:``. + +To use a ``MongoCredential`` object for ``MONGODB-AWS`` authentication, perform +the following steps: + +1. Specify the authentication mechanism. +#. Supply the credentials. + +To specify the authentication mechanism by using a ``MongoCredential`` object, +call the ``MongoCredential.createAwsCredential()`` factory method +and add the ``MongoCredential`` instance to your ``MongoClient``, as shown +in the following example: + +.. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-aws-mcred + :end-before: end-aws-mcred + :emphasize-lines: 1, 9 + +If you must specify an AWS session token, pass it to the +`withMechanismProperty() <{+core-api+}/MongoCredential.html#withMechanismProperty(java.lang.String,T)>`__ +method, as shown in the following example: + +.. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-aws-mcred-wmechprop + :end-before: end-aws-mcred-wmechprop + :emphasize-lines: 1, 2, 10 + +To refresh your credentials, you can declare a ``Supplier`` lambda expression +that returns new credentials, as shown in the following example: + +.. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-aws-lambda-expression + :end-before: end-aws-lambda-expression + :emphasize-lines: 4-6, 9 + +If you must provide AWS IAM credentials in a connection string, you can add +it to your ``MongoClientSettings`` object by calling the `applyConnectionString() <{+core-api+}/MongoClientSettings.Builder.html#applyConnectionString(com.mongodb.ConnectionString)>`__ +method: + +.. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-aws-apply-connect-string + :end-before: end-aws-apply-connect-string + :emphasize-lines: 2, 5 + +Additional Information +---------------------- + +To learn more about authenticating to MongoDB, see +:manual:`Authentication ` in the {+mdb-server+} manual. + +To learn more about creating a ``MongoClient`` object by using the +{+driver-short+}, see the :ref:`kotlin-sync-mongoclient` guide. \ No newline at end of file diff --git a/source/security/authentication/scram.txt b/source/security/authentication/scram.txt new file mode 100644 index 00000000..c6072caa --- /dev/null +++ b/source/security/authentication/scram.txt @@ -0,0 +1,189 @@ +.. _kotlin-sync-auth-scram: + +==================== +SCRAM Authentication +==================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: salt, default, code example + +Overview +-------- + +**Salted Challenge Response Authentication Mechanism (SCRAM)** is a family of +authentication mechanisms that use a challenge-response mechanism to authenticate +the user. ``SCRAM-SHA-256``, which uses the ``SHA-256`` algorithm to hash your password, is the +default authentication mechanism in {+mdb-server+} version 4.0 +and later. ``SCRAM-SHA-1``, which uses the ``SHA-1`` algorithm, is the default +authentication mechanism in {+mdb-server+} versions earlier than 4.0. + +You can use ``SCRAM`` to authenticate to MongoDB Atlas, MongoDB +Enterprise Advanced, and MongoDB Community Edition. + +.. tip:: SCRAM Mechanisms + + To learn more about the ``SCRAM`` family of authentication mechanisms, see + `RFC 5802 `__ and + :wikipedia:`Salted Challenge Response Authentication Mechanism ` + on Wikipedia. + + For more information about the MongoDB implementation of ``SCRAM``, see + :manual:`SCRAM ` in the {+mdb-server+} manual. + +.. _kotlin-sync-auth-default: +.. _kotlin-sync-auth-scramsha256: + +Specify SCRAM-SHA-256 Authentication +------------------------------------ + +``SCRAM-SHA-256``, as defined by `RFC 7677 `__, +encrypts your username and password with the ``SHA-256`` algorithm to authenticate +your user. This is the default authentication mechanism. + +The examples in this section show how to specify this default authentication +mechanism and use the following placeholder values: + +- ``db_username``: Your MongoDB database username. +- ``db_password``: Your MongoDB database user's password. +- ``hostname``: The network address of your MongoDB deployment, open to your client. +- ``port``: The port number of your MongoDB deployment. +- ``authenticationDb``: The MongoDB database that contains your user's + authentication data. If you omit this parameter, the driver uses the + default value ``admin``. + +Select the :guilabel:`Connection String` or the :guilabel:`MongoCredential` +tab below for instructions and sample code for specifying this authentication +mechanism: + +.. tabs:: + + .. tab:: + :tabid: Connection String + + To specify the default authentication mechanism by using a connection + string, omit the mechanism as shown in the following example: + + .. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :start-after: start-default-cred-string + :end-before: end-default-cred-string + :dedent: + + .. tab:: + :tabid: MongoCredential + + To specify the default authentication mechanism by using the + ``MongoCredential`` class, use the ``createCredential()`` method + as shown in the following example: + + .. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :start-after: start-default-mongo-cred + :end-before: end-default-mongo-cred + :dedent: + +Alternatively, you can explicitly specify the ``SCRAM-SHA-256`` authentication mechanism. +Select the :guilabel:`Connection String` or the :guilabel:`MongoCredential` +tab below for instructions and sample code for specifying this authentication +mechanism: + +.. tabs:: + + .. tab:: + :tabid: Connection String + + To specify the ``SCRAM-SHA-256`` authentication mechanism by using a + connection string, assign the ``authMechanism`` parameter the value + ``SCRAM-SHA-256`` in your connection string as shown in the following example: + + .. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-scramsha256-cred-string + :end-before: end-scramsha256-cred-string + + .. tab:: + :tabid: MongoCredential + + To specify the default authentication mechanism by using the + ``MongoCredential`` class, use the + `createScramSha256Credential() <{+core-api+}/MongoCredential.html#createScramSha256Credential(java.lang.String,java.lang.String,char[])>`__ + method as shown in the following example: + + .. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-scramsha256-mongo-cred + :end-before: end-scramsha256-mongo-cred + +.. _kotlin-sync-auth-scramsha1: + +Specify SCRAM-SHA-1 Authentication +---------------------------------- + +``SCRAM-SHA-1``, as defined by `RFC 5802 `__, +encrypts your username and password with the ``SHA-1`` algorithm to authenticate +your user. + +The examples in this section show how to specify this authentication +mechanism and use the following placeholder values: + +- ``db_username``: Your MongoDB database username. +- ``db_password``: Your MongoDB database user's password. +- ``hostname``: The network address of your MongoDB deployment, open to your client. +- ``port``: The port number of your MongoDB deployment. +- ``authenticationDb``: The MongoDB database that contains your user's + authentication data. If you omit this parameter, the driver uses the + default value ``admin``. + +Select the :guilabel:`Connection String` or the :guilabel:`MongoCredential` +tab below for instructions and sample code for specifying the ``SCRAM-SHA-1`` authentication +mechanism: + +.. tabs:: + + .. tab:: + :tabid: Connection String + + To specify the ``SCRAM-SHA-1`` authentication mechanism by using a + connection string, assign the ``authMechanism`` parameter the value + ``SCRAM-SHA-1`` in your connection string as shown in the following example: + + .. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-scramsha1-cred-string + :end-before: end-scramsha1-cred-string + + .. tab:: + :tabid: MongoCredential + + To specify the default authentication mechanism by using the + ``MongoCredential`` class, use the + `createScramSha1Credential() <{+core-api+}/MongoCredential.html#createScramSha1Credential(java.lang.String,java.lang.String,char[])>`__ + method as shown in the following example: + + .. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-scramsha1-mongo-cred + :end-before: end-scramsha1-mongo-cred + +Additional Information +---------------------- + +To learn more about authenticating to MongoDB, see +:manual:`Authentication ` in the {+mdb-server+} manual. + +To learn more about creating a ``MongoClient`` object by using the +{+driver-short+}, see the :ref:`kotlin-sync-mongoclient` guide. \ No newline at end of file diff --git a/source/security/authentication/x509.txt b/source/security/authentication/x509.txt new file mode 100644 index 00000000..3e4079ec --- /dev/null +++ b/source/security/authentication/x509.txt @@ -0,0 +1,90 @@ +.. _kotlin-sync-auth-x509: + +==================== +X.509 Authentication +==================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: certificate, code example + +Overview +-------- + +In the **X.509** authentication mechanism, the server and client use the +:wikipedia:`TLS ` protocol to exchange X.509 public-key +certificates. You can use this mechanism to authenticate to MongoDB Atlas, MongoDB +Enterprise Advanced, and MongoDB Community Edition. + +.. tip:: X.509 Mechanism + + To learn how to use TLS/SSL with the {+driver-short+}, + see the :ref:`kotlin-sync-tls` guide. + + For more information about X.509 certificates, see + :manual:`Use x.509 Certificates to Authenticate Clients on Self-Managed Deployments + ` in the {+mdb-server+} manual. + +Specify X.509 Authentication +---------------------------- + +The examples in this section show how to specify the ``X.509`` authentication mechanism +and use the following placeholder values: + +* ``hostname``: The network address of your MongoDB deployment, open to your client. +* ``port``: The port number of your MongoDB server. +* ``authenticationDb``: The MongoDB database that contains your user's + authentication data. If you omit this parameter, the driver uses the + default value ``admin``. + +Select the :guilabel:`Connection String` or the :guilabel:`MongoCredential` +tab below for instructions and sample code for specifying this authentication +mechanism: + +.. tabs:: + + .. tab:: + :tabid: Connection String + + To specify the ``X.509`` authentication mechanism by using a connection + string, set the ``authMechanism`` parameter to ``MONGODB-X509`` + and the ``tls`` parameter to ``true`` as shown in the following example: + + .. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-x509-connect-string + :end-before: end-x509-connect-string + + .. tab:: + :tabid: MongoCredential + + To specify the ``X.509`` authentication mechanism by using the + ``MongoCredential`` class, use the + `createMongoX509Credential() <{+core-api+}/MongoCredential.html#createMongoX509Credential(java.lang.String)>`__ + and `applyToSslSettings() <{+core-api+}/MongoClientSettings.Builder.html#applyToSslSettings(com.mongodb.Block)>`__ + builder methods as shown in the following example: + + .. literalinclude:: /includes/security/authentication.kt + :language: kotlin + :dedent: + :start-after: start-x509-mcred + :end-before: end-x509-mcred + +Additional Information +---------------------- + +To learn more about authenticating to MongoDB, see +:manual:`Authentication ` in the {+mdb-server+} manual. + +To learn more about creating a ``MongoClient`` object by using the +{+driver-short+}, see the :ref:`kotlin-sync-mongoclient` guide. \ No newline at end of file From 0ce6dd967a628c30b6a15ae35f3c88da41e88417 Mon Sep 17 00:00:00 2001 From: Nora Reidy Date: Thu, 24 Jul 2025 11:27:12 -0400 Subject: [PATCH 14/22] DOCSP-51283: noindex short pages (#124) --- snooty.toml | 1 - source/api.txt | 3 +++ source/security.txt | 3 +++ 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/snooty.toml b/snooty.toml index 6dd53417..b69d414b 100644 --- a/snooty.toml +++ b/snooty.toml @@ -17,7 +17,6 @@ toc_landing_pages = [ "/connect/connection-options", "/logging-and-monitoring", "/databases-and-collections", - "/api", "/security/authentication" ] diff --git a/source/api.txt b/source/api.txt index 60030787..31d87a6c 100644 --- a/source/api.txt +++ b/source/api.txt @@ -1,3 +1,6 @@ +.. meta:: + :robots: noindex, nosnippet + .. _kotlin-sync-api-docs: ================= diff --git a/source/security.txt b/source/security.txt index 5c605dcb..7f81ffeb 100644 --- a/source/security.txt +++ b/source/security.txt @@ -1,3 +1,6 @@ +.. meta:: + :robots: noindex, nosnippet + .. _kotlin-sync-security: ================ From 6481fad3ec6c8e2e7ccf5704dec13b165b756e47 Mon Sep 17 00:00:00 2001 From: shuangela Date: Thu, 24 Jul 2025 15:41:29 -0400 Subject: [PATCH 15/22] DOCSP-52259-edit-aggregation-page (#123) * remove duplicate info from aggregation guide * nr feedback * remove extra space --- source/aggregation.txt | 36 ++++-------------------------------- 1 file changed, 4 insertions(+), 32 deletions(-) diff --git a/source/aggregation.txt b/source/aggregation.txt index 9fefce6b..360b8589 100644 --- a/source/aggregation.txt +++ b/source/aggregation.txt @@ -202,38 +202,10 @@ an aggregation pipeline that contains one of the following pipeline stages: - ``$search`` - ``$searchMeta`` -To learn more about Atlas Search pipeline stages, see :atlas:`Choose the -Aggregation Pipeline Stage ` in the Atlas -documentation. - -Create a Pipeline Search Stage -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can create the search criteria in your Atlas Search pipeline stage -by using Search operators. - -.. sharedinclude:: dbx/jvm/atlas-search-operator-helpers.rst - - .. replacement:: as-idx-link - - the :ref:`kotlin-sync-atlas-search-index` guide - - .. replacement:: atlas-query-operators-example - - .. io-code-block:: - - .. input:: /includes/aggregation/aggregation.kt - :language: kotlin - :start-after: // start-atlas-searchoperator-helpers - :end-before: // end-atlas-searchoperator-helpers - :dedent: - - .. output:: - :language: console - :visible: false - - Document{{_id=..., genres=[Comedy, Romance], title=Love at First Bite, year=1979}} - Document{{_id=..., genres=[Comedy, Drama], title=Love Affair, year=1994}} +To learn more about Atlas Search pipeline stages, see :atlas:`Choose the Aggregation +Pipeline Stage ` in the Atlas documentation. To view +examples that use the {+driver-short+} to create Atlas Search pipeline search stages, see +the :ref:`kotlin-sync-atlas-search` guide. Additional Information ---------------------- From 48d1336078da023e4d4e07202da4b124b9b51283 Mon Sep 17 00:00:00 2001 From: shuangela Date: Thu, 24 Jul 2025 16:34:26 -0400 Subject: [PATCH 16/22] update credentials (#125) --- source/connect/connection-targets.txt | 4 ++-- source/connect/mongoclient.txt | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/source/connect/connection-targets.txt b/source/connect/connection-targets.txt index 80ac95ab..632a8d07 100644 --- a/source/connect/connection-targets.txt +++ b/source/connect/connection-targets.txt @@ -30,8 +30,8 @@ To connect to a MongoDB deployment on Atlas, include the following elements in your connection string: - The URL of your Atlas cluster -- Your MongoDB username -- Your MongoDB password +- Your MongoDB database username +- Your MongoDB database password Then, pass your connection string to the ``MongoClient`` constructor. diff --git a/source/connect/mongoclient.txt b/source/connect/mongoclient.txt index cc271cf6..fc7f195b 100644 --- a/source/connect/mongoclient.txt +++ b/source/connect/mongoclient.txt @@ -52,10 +52,10 @@ A standard connection string includes the following components: - Required. A prefix that identifies this as a string in the standard connection format. - * - ``username:password`` + * - ``db_username:db_password`` - Optional. Authentication credentials. If you include these, the client - authenticates the user against the database specified in ``authSource``. + authenticates the database user against the database specified in ``authSource``. For more information about the ``authSource`` connection option, see :ref:`kotlin-sync-auth`. @@ -67,7 +67,7 @@ A standard connection string includes the following components: * - ``/defaultauthdb`` - Optional. The authentication database to use if the - connection string includes ``username:password@`` + connection string includes ``db_username:db_password@`` authentication credentials but not the ``authSource`` option. If you don't include this component, the client authenticates the user against the ``admin`` database. From 90840899889af3f7abeaded6e8fa8b6cc682aaef Mon Sep 17 00:00:00 2001 From: shuangela Date: Fri, 25 Jul 2025 10:10:00 -0400 Subject: [PATCH 17/22] DOCSP-51348-atlas-search-page (#122) * atlas search page * fix link * sa feedback * nathan feedback --- source/atlas-search.txt | 154 +++++++++++++++++- .../includes/aggregation/search-meta-agg.kt | 42 +++++ source/includes/atlas-search.kt | 41 +++++ 3 files changed, 236 insertions(+), 1 deletion(-) create mode 100644 source/includes/aggregation/search-meta-agg.kt create mode 100644 source/includes/atlas-search.kt diff --git a/source/atlas-search.txt b/source/atlas-search.txt index 483dc91b..2baccd86 100644 --- a/source/atlas-search.txt +++ b/source/atlas-search.txt @@ -2,4 +2,156 @@ ========================= Run an Atlas Search Query -========================= \ No newline at end of file +========================= + +.. 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 + +Overview +-------- + +In this guide, you can learn how to use the {+driver-short+} to +run :atlas:`Atlas Search ` queries on a collection. +Atlas Search enables you to perform full-text searches on collections +hosted on MongoDB Atlas. Atlas Search indexes specify the behavior of the +search and which fields to index. + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``movies`` collection in the ``sample_mflix`` +database from the :atlas:`Atlas sample datasets `. To learn how to +create a free MongoDB Atlas cluster and load the sample datasets, see the +:atlas:`Get Started with Atlas ` guide. To learn more about +aggregation operations and builders, see the :ref:`kotlin-sync-aggregation` guide. + +Run an Atlas Search Query +------------------------- + +This section shows how to create an aggregation pipeline to run an +Atlas Search query on a collection. You can use the ``Aggregates.search()`` builder +method to create a ``$search`` pipeline stage, which specifies the search +criteria. Then, call the ``aggregate()`` method and pass your pipeline as a +parameter. + +.. note:: Only Available on Atlas for MongoDB v4.2 and later + + This aggregation pipeline operator is only available for collections hosted + on :atlas:`MongoDB Atlas ` clusters running v4.2 or later that are + covered by an :atlas:`Atlas Search index `. + Learn more about the required setup and the functionality of this operator + from the :atlas:`Atlas Search ` documentation. + +Before running an Atlas Search query, you must create an Atlas Search index +on your collection. To learn how to programmatically create an Atlas Search +index, see the :ref:`kotlin-sync-atlas-search-index-create` section in the Indexes guide. + +Atlas Search Example +~~~~~~~~~~~~~~~~~~~~ + +This example runs an Atlas Search query by performing the +following actions: + +- Constructs a ``$search`` stage by using the ``Aggregates.search()`` builder method, + instructing the driver to query for documents in which the ``title`` + field contains the word ``"Alabama"`` + +- Constructs a ``$project`` stage by using the ``Aggregates.project()`` builder method, + instructing the driver to include the ``title`` field in the query results + +- Passes the pipeline stages to the ``aggregate()`` method and prints the results + +.. io-code-block:: + :copyable: + + .. input:: /includes/atlas-search.kt + :start-after: begin-atlas-search + :end-before: end-atlas-search + :language: kotlin + :dedent: + + .. output:: + :language: console + :visible: false + + {"_id": {"$oid": "..."}, "title": "Alabama Moon"} + {"_id": {"$oid": "..."}, "title": "Crazy in Alabama"} + {"_id": {"$oid": "..."}, "title": "Sweet Home Alabama"} + +Atlas Search Metadata +--------------------- + +Use the ``searchMeta()`` method to create a :manual:`$searchMeta +` pipeline stage, which returns +only the metadata from the Atlas full-text search results. + +.. tip:: Only Available on Atlas for MongoDB v4.4.11 and later + + This aggregation pipeline operator is available only + on :atlas:`MongoDB Atlas ` clusters running v4.4.11 and later. + +The following example shows the ``near`` metadata for an Atlas Search +aggregation stage: + +.. literalinclude:: /includes/aggregation/search-meta-agg.kt + :start-after: // begin atlasSearchMeta + :end-before: // end atlasSearchMeta + :language: kotlin + :dedent: + +.. _kotlin-atlas-search-helpers: + +Create Pipeline Search Stages +----------------------------- + +.. sharedinclude:: dbx/jvm/atlas-search-operator-helpers.rst + + .. replacement:: as-idx-link + + the :ref:`kotlin-sync-atlas-search-index-create` section of the Indexes guide + + .. replacement:: atlas-query-operators-example + + .. io-code-block:: + + .. input:: /includes/aggregation/aggregation.kt + :language: kotlin + :start-after: // start-atlas-searchoperator-helpers + :end-before: // end-atlas-searchoperator-helpers + :dedent: + + .. output:: + :language: console + :visible: false + + {"_id": ..., "genres": ["Comedy", "Romance"], "title": "Love at First Bite", "year": 1979} + {"_id": ..., "genres": ["Comedy", "Drama"], "title": "Love Affair", "year": 1994} + +Additional Information +---------------------- + +To learn more about Atlas Search, see :atlas:`Atlas Search ` +in the Atlas documentation. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about the methods mentioned in this guide, see +the following API documentation: + +- `aggregate() <{+driver-api+}/-mongo-collection/aggregate.html>`__ +- `Aggregates.search() <{+core-api+}/client/model/Aggregates.html#search(com.mongodb.client.model.search.SearchCollector)>`__ +- `Aggregates.searchMeta() <{+core-api+}/client/model/Aggregates.html#searchMeta(com.mongodb.client.model.search.SearchCollector)>`__ +- `Aggregates.project() <{+core-api+}/client/model/Aggregates.html#project(org.bson.conversions.Bson)>`__ +- `SearchOperator <{+core-api+}/client/model/search/SearchOperator.html>`__ \ No newline at end of file diff --git a/source/includes/aggregation/search-meta-agg.kt b/source/includes/aggregation/search-meta-agg.kt new file mode 100644 index 00000000..0ec67aab --- /dev/null +++ b/source/includes/aggregation/search-meta-agg.kt @@ -0,0 +1,42 @@ +package org.example + +import com.mongodb.ConnectionString +import com.mongodb.kotlin.client.MongoClient +import com.mongodb.MongoClientSettings +import com.mongodb.client.model.Aggregates.searchMeta +import com.mongodb.client.model.search.SearchOperator +import com.mongodb.client.model.search.SearchPath.fieldPath +import com.mongodb.kotlin.client.MongoCollection +import org.bson.Document + +fun runAtlasTextSearchMeta(collection: MongoCollection) { + val textSearchMeta = + // begin atlasSearchMeta + searchMeta( + SearchOperator.near(2010, 1, fieldPath("year")) + ) + // end atlasSearchMeta + + val aggregateStages = listOf(textSearchMeta) + println("aggregateStages: $aggregateStages") + + collection.aggregate(aggregateStages).forEach { result -> + println(result) + } +} + +fun main() { + val uri = "" + + val settings = MongoClientSettings.builder() + .applyConnectionString(ConnectionString(uri)) + .retryWrites(true) + .build() + + MongoClient.create(settings).use { mongoClient -> + val database = mongoClient.getDatabase("sample_mflix") + val collection = database.getCollection("movies") + + runAtlasTextSearchMeta(collection) + } +} \ No newline at end of file diff --git a/source/includes/atlas-search.kt b/source/includes/atlas-search.kt new file mode 100644 index 00000000..53c0b628 --- /dev/null +++ b/source/includes/atlas-search.kt @@ -0,0 +1,41 @@ +// Runs an Atlas Search query by using the Kotlin sync driver + +package org.example + +import com.mongodb.ConnectionString +import com.mongodb.kotlin.client.MongoClient +import com.mongodb.MongoClientSettings +import com.mongodb.client.model.Aggregates.project +import com.mongodb.client.model.Aggregates.search +import com.mongodb.client.model.Projections +import com.mongodb.client.model.search.SearchOperator +import com.mongodb.client.model.search.SearchPath.fieldPath +import org.bson.Document +import org.bson.conversions.Bson + +fun main() { + val uri = "" + + val settings = MongoClientSettings.builder() + .applyConnectionString(ConnectionString(uri)) + .retryWrites(true) + .build() + + val mongoClient = MongoClient.create(settings) + val database = mongoClient.getDatabase("sample_mflix") + val collection = database.getCollection("movies") + + // begin-atlas-search + val pipeline: List = listOf( + search(SearchOperator.text( + fieldPath("title"), "Alabama")), + project(Projections.include("title")) + ) + + val results = collection.aggregate(pipeline) + + results.forEach { doc -> + println(doc.toJson()) + } + // end-atlas-search +} \ No newline at end of file From f337e8f45289e35e85e46d9b36efedc6221d7e33 Mon Sep 17 00:00:00 2001 From: Nora Reidy Date: Fri, 25 Jul 2025 14:10:19 -0400 Subject: [PATCH 18/22] DOCSP-51349: Upgrade guide (#127) * DOCSP-51349: Upgrade guide * edits * edits --- source/reference/upgrade.txt | 388 ++++++++++++++++++++++++++++++++++- 1 file changed, 387 insertions(+), 1 deletion(-) diff --git a/source/reference/upgrade.txt b/source/reference/upgrade.txt index d1c97a35..2c8d8ae1 100644 --- a/source/reference/upgrade.txt +++ b/source/reference/upgrade.txt @@ -8,4 +8,390 @@ Upgrade Driver Versions :local: :backlinks: none :depth: 1 - :class: singlecol \ No newline at end of file + :class: singlecol + +.. meta:: + :keywords: backwards compatibility, update + +Overview +-------- + +In this section, you can identify the changes you must +make to your application to upgrade your driver to a new version. + +Before you upgrade, perform the following actions: + +- Ensure the new driver version is compatible with the {+mdb-server+} versions + your application connects to and the Java Runtime Environment (JRE) your + application runs on. To view compatibility information, see the + :ref:`Compatibility ` page. +- Address any breaking changes between the current version of the driver + your application is using and your planned upgrade version in the + :ref:`Breaking Changes ` section. To learn + more about {+mdb-server+} release compatibility changes, see the + :ref:`` section. + +.. tip:: + + To minimize the number of changes your application might require when + you upgrade driver versions in the future, use the + :ref:`{+stable-api+}. ` + +.. _kotlin-sync-breaking-changes: + +Breaking Changes +---------------- + +A breaking change is a modification in a convention or behavior in +a specific version of the driver that might prevent your application from +working properly if not addressed before upgrading. + +The breaking changes in this section are categorized by the driver version that +introduced them. When upgrading driver versions, address all the breaking +changes between the current and upgrade versions. For example, if you +are upgrading the driver from v5.0 to v5.5, address all breaking changes from +the versions after v5.0 including any listed for v5.5. + +.. _kotlin-sync-breaking-changes-v5.5: + +Version 5.5 Breaking Changes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- The driver is no longer compatible with {+mdb-server+} version + 4.0. To learn more about this change, see the + :ref:`kotlin-sync-server-release-change-v5.5` section. + +.. _kotlin-sync-breaking-changes-v5.2: + +Version 5.2 Breaking Changes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This driver version introduces the following breaking changes: + +- Drops support for {+mdb-server+} v3.6. To learn more about this change, + see the :ref:`` section. + +- Revises the `mongodb-crypt `__ + dependency versioning to match the versioning for the JVM drivers. Future versions of + ``mongodb-crypt`` are released alongside the driver and share the same version number. + You must upgrade your ``mongodb-crypt`` dependency to v5.2.0 when upgrading your driver for + this release. + +.. _kotlin-sync-breaking-changes-v5.1: + +Version 5.1 Breaking Changes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This driver version introduces the following breaking changes: + +- When using the ``MONGODB-OIDC`` authentication mechanism, you cannot + include comma characters in the ``authMechanismProperties`` connection + string value. If your ``authMechanismProperties`` value includes a comma, + pass the value as a connection option in a ``MongoClientSettings`` instance. + +.. _kotlin-sync-breaking-changes-v5.0: + +Version 5.0 Breaking Changes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This driver version introduces the following breaking changes: + +- Introduces the following changes to the ``ConnectionId`` class: + + - The ``ConnectionId`` constructor now accepts a value of type ``long`` as its second + parameter instead of type ``int``. Similarly, the constructor now accepts a value of + type ``Long`` as its third parameter instead of type ``Integer``. Because this change breaks + binary compatibility, recompile any existing code that calls the + ``ConnectionId`` constructor. + + - The ``withServerValue()`` method now accepts a parameter of type ``long`` rather than + type ``int``. Because this change breaks binary compatibility, you must recompile any code + that calls the ``withServerValue()`` method. + + - The ``getServerValue()`` method now returns a value of type ``Long`` instead of type + ``Integer``. Similarly, the ``getLocalValue()`` method returns a value of type + ``long`` instead of type ``int``. Because this change breaks both binary and source + compatibility, update any source code that uses these methods and rebuild your binary. + +- Replaces the following record annotations from the + ``org.bson.codecs.record.annotations`` package with + annotations of the same name from the ``org.bson.codecs.pojo.annotations`` package: + + - ``BsonId`` + - ``BsonProperty`` + - ``BsonRepresentation`` + +- Changes the data type of the ``connectTimeout`` timeout duration parameter for the + ``SocketSettings.Builder.connectTimeout()`` and + ``SocketSettings.Builder.readTimeout()`` methods. The data type of this + parameter is now ``long`` instead of ``int``. + + In earlier versions, this parameter is of type ``int`` for both methods. This + change breaks binary compatibility and requires recompiling, but does not + require code changes. + +- Removes the ``Filters.eqFull()`` method, released + exclusively in ``Beta``, which allowed you + to construct an equality filter when performing a vector search. + Instead, you can use the ``Filters.eq()`` method when instantiating a + ``VectorSearchOptions`` type, as shown in the following code: + + .. code-block:: kotlin + + val opts = vectorSearchOptions().filter(eq("x", 8)) + +- Changes how ``ClusterSettings`` computes the ``ClusterConnectionMode`` + setting, making it more consistent by using the specified + replica set name, regardless of how it is configured. Previously, the driver + considered the replica set name only if it was set in the connection string. + + For example, the following two code samples both return the value + ``ClusterConnectionMode.MULTIPLE``. Previously, the second example returned + ``ClusterConnectionMode.SINGLE``. + + .. code-block:: kotlin + + ClusterSettings.builder() + .applyConnectionString(ConnectionString("mongodb://127.0.0.1:27017/?replicaSet=replset")) + .build() + .mode + + .. code-block:: kotlin + + ClusterSettings.builder() + .hosts(listOf(ServerAddress("127.0.0.1", 27017))) + .requiredReplicaSetName("replset") + .build() + .mode + +- ``BsonDecimal128`` values respond to method calls in the same way as + ``Decimal128`` values. ``BsonDecimal128.isNumber()`` now returns ``true`` and + ``BsonDecimal128.asNumber()`` returns the equivalent ``BsonNumber``. + +- Removes the `ServerAddress <{+core-api+}/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``. + +- Removes the `UnixServerAddress <{+core-api+}/UnixServerAddress.html>`__ + methods ``getSocketAddress()`` and ``getUnixSocketAddress()``. + + Instead of ``getSocketAddress()``, use the ``getByName()`` instance + method of ``java.net.InetAddress``. + + 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`` class, see the `UnixSocketAddress `__ API documentation. + +- Removes the ``Parameterizable`` interface. 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. + +- Removes the ``isSlaveOk()`` method from the + ``ReadPreference`` and ``TaggableReadPreference`` classes. To check whether a read preference allows + reading from a secondary member of a replica set, use the ``isSecondaryOk()`` methods from + these classes instead. + +- Removes the ``DBCollection.getStats()`` and ``DBCollection.isCapped()`` + helper methods for the ``collStats`` command. Instead of these methods, you can use the + ``$collStats`` aggregation pipeline stage. + +- Removes the ``MapCodec`` and ``IterableCodec`` classes. + Instead of ``MapCodec``, use ``MapCodecProvider``. Instead of ``IterableCodec``, + use ``CollectionCodecProvider``, or ``IterableCodecProvider`` for ``Iterable`` + types that aren't ``Collection`` types. + +- Removes the ``sharded()`` and ``nonAtomic()`` methods from the + ``MapReducePublisher`` and ``MapReduceIterable`` classes. + +- Removes the following methods for use with ``geoHaystack`` indexes: + + - ``Indexes.geoHaystack()`` + - ``IndexOptions.getBucketSize()`` + - ``IndexOptions.bucketSize()`` + + Instead, you can use the ``$geoNear`` aggregation pipeline stage or a geospatial + query operator on a 2d index. For more information, see the + :manual:`Geospatial Queries ` page in the {+mdb-server+} manual. + +- Removes the ``oplogReplay`` option from find operations. The + following ``oplogReplay`` methods are no longer available: + + - ``DBCursor.oplogReplay()`` + - ``DBCollectionFindOptions.isOplogReplay()`` + - ``DBCollectionFindOptions.oplogReplay()`` + - ``FindPublisher.oplogReplay()`` + - ``FindIterable.oplogReplay()`` + +- Removes the following ``Exception`` constructors: + + - ``MongoBulkWriteException(BulkWriteResult, List, WriteConcernError, ServerAddress)`` + - ``MongoCursorNotFoundException(long, ServerAddress)`` + - ``MongoQueryException(ServerAddress, int, String)`` + - ``MongoQueryException(ServerAddress, int, String, String)`` + - ``MongoQueryException(MongoCommandException)`` + +- Removes the following overloads for the ``BulkWriteResult.acknowledged()`` method: + + - ``acknowledged(Type, int, List)`` + - ``acknowledged(Type, int, Integer, List)`` + - ``acknowledged(int, int, int, Integer, List)`` + +- Removes the following ``ChangeStreamDocument`` constructors: + + - ``ChangeStreamDocument(String, BsonDocument, BsonDocument, BsonDocument, + TDocument, TDocument, BsonDocument, ...)`` + - ``ChangeStreamDocument(String, BsonDocument, BsonDocument, BsonDocument, + TDocument, BsonDocument, BsonTimestamp, ...)`` + - ``ChangeStreamDocument(OperationType, BsonDocument, BsonDocument, BsonDocument, + TDocument, BsonDocument, BsonTimestamp, ...)`` + +- Removes the following constructors for events: + + - ``CommandEvent(RequestContext, int, ConnectionDescription, String)`` + - ``CommandEvent(int, ConnectionDescription, String)`` + - ``CommandEvent(RequestContext, long, int, ConnectionDescription, String)`` + - ``CommandFailedEvent(RequestContext, int, ConnectionDescription, String, + long, Throwable)`` + - ``CommandFailedEvent(int, ConnectionDescription, String, long, Throwable)`` + - ``CommandStartedEvent(RequestContext, int, ConnectionDescription, String, + String, BsonDocument)`` + - ``CommandStartedEvent(int, ConnectionDescription, String, String, BsonDocument)`` + - ``CommandSucceededEvent(RequestContext, int, ConnectionDescription, String, + BsonDocument, long)`` + - ``CommandSucceededEvent(int, ConnectionDescription, String, BsonDocument, long)`` + - ``ConnectionCheckedInEvent(ConnectionId)`` + - ``ConnectionCheckedOutEvent(ConnectionId, long)`` + - ``ConnectionCheckedOutEvent(ConnectionId)`` + - ``ConnectionCheckOutFailedEvent(ServerId, long, Reason)`` + - ``ConnectionCheckOutFailedEvent(ServerId, Reason)`` + - ``ConnectionCheckOutStartedEvent(ServerId)`` + - ``ConnectionReadyEvent(ConnectionId)`` + - ``ServerHeartbeatFailedEvent(ConnectionId, long, Throwable)`` + - ``ServerHeartbeatSucceededEvent(ConnectionId, BsonDocument, long)`` + +- Removes the ``errorLabels`` option from the ``WriteConcernError`` + class. This includes the ``addLabel()`` and ``getErrorLabels()`` methods and the + constructor that includes an ``errorLabels`` parameter. Instead, you can use + the error labels included in the ``MongoException`` object that contains the + ``WriteConcernError``. + +- Removes the following classes from the + ``com.mongodb.event`` package: + + - ``ConnectionAddedEvent`` + - ``ConnectionPoolOpenedEvent`` + - ``ConnectionRemovedEvent`` + - ``ClusterListenerAdapter`` + - ``ConnectionPoolListenerAdapter`` + - ``ServerListenerAdapter`` + - ``ServerMonitorListenerAdapter`` + + The driver also removes the following related methods from the + ``ConnectionPoolListener`` interface: + + - ``connectionAdded()`` + - ``connectionPoolOpened()`` + - ``connectionRemoved()`` + + For more information about the ``com.mongodb.event`` package, see the + `API documentation. <{+core-api+}/event/package-summary.html>`__ + +.. _kotlin-sync-breaking-changes-v5.0-list-collections: + +- Adds the ``authorizedCollection`` option for the ``listCollections`` command. + This introduces a breaking binary change in the ``MongoDatabase.listCollectionNames()`` + method. This change does not require any changes to source code, but you must + recompile any code that uses this method. + +- Removes the following methods and types related to the + `Stream + `__ + interface: + + - ``MongoClientSettings.Builder.streamFactoryFactory()`` method. + Use the ``MongoClientSettings.Builder.transportSettings()`` method instead. + - ``MongoClientSettings.getStreamFactoryFactory()`` method. + Use the ``MongoClientSettings.getTransportSettings()`` method instead. + - ``NettyStreamFactoryFactory`` class. + Instead, call the ``TransportSettings.nettyBuilder()`` method to create + a ``NettyTransportSettings`` object. Then, call the ``MongoClientSettings.Builder.transportSettings()`` + method to apply the settings. + - ``NettyStreamFactory`` class. + - ``AsynchronousSocketChannelStreamFactory`` class. + - ``AsynchronousSocketChannelStreamFactoryFactory`` class. + - ``BufferProvider`` interface. + - ``SocketStreamFactory`` class. + - ``Stream`` interface. + - ``StreamFactory`` interface. + - ``StreamFactoryFactory`` interface. + - ``TlsChannelStreamFactoryFactory`` class. + +.. tip:: + + To view breaking changes for earlier driver versions, see the + :github:`Release Notes ` in the + ``mongo-java-driver`` GitHub repository. + +.. _kotlin-sync-server-release-changes: + +Server Release Compatibility Changes +------------------------------------ + +A server release compatibility change is a modification +to the {+driver-short+} that discontinues support for a set of +{+mdb-server+} versions. + +The driver discontinues support for a {+mdb-server+} version after it reaches +end-of-life (EOL). + +To learn more about the MongoDB support for EOL products, +see the `Legacy Support Policy `__. + +.. _kotlin-sync-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 +MongoDB deployment running {+mdb-server+} v8.1 or later. Starting in {+mdb-server+} v8.1, +the ``buildinfo`` command requires authentication, causing an +incompatibility with the v3.x driver. + +.. _kotlin-sync-server-release-change-v5.5: + +Driver Version 5.5 Server Support Changes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The v5.5 driver drops support for {+mdb-server+} 4.0. +To use the v5.5 driver, you must connect to {+mdb-server+} 4.2 or later. To +learn how to upgrade your {+mdb-server+} deployment, see +:manual:`Release Notes ` in the {+mdb-server+} manual. + +.. _kotlin-sync-server-release-change-v5.2: + +Driver Version 5.2 Server Support Changes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The v5.2 driver drops support for {+mdb-server+} 3.6. +To use the v5.2 driver, you must connect to {+mdb-server+} 4.0 or later. To +learn how to upgrade your {+mdb-server+} deployment, see +:manual:`Release Notes ` in the {+mdb-server+} manual. + +.. _kotlin-sync-server-release-change-v4.8: + +Driver Version 4.8 Server Support Changes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The v4.8 driver drops support for {+mdb-server+} 3.4 and earlier. +To use the v4.8 driver, you must connect to {+mdb-server+} 3.6 or later. To learn +how to upgrade your {+mdb-server+} deployment, see :manual:`Release +Notes ` in the {+mdb-server+} manual. From 33fb65a3c1b6fd3d9db96dd55c7af97d0df060e5 Mon Sep 17 00:00:00 2001 From: Michael Morisi Date: Fri, 25 Jul 2025 16:29:56 -0400 Subject: [PATCH 19/22] DOCSP-51347: Server Selection (#118) --- source/connect/connection-options.txt | 1 + .../connection-options/server-selection.txt | 145 ++++++++++++++++++ source/includes/connect/ServerSelection.kt | 31 ++++ 3 files changed, 177 insertions(+) create mode 100644 source/connect/connection-options/server-selection.txt create mode 100644 source/includes/connect/ServerSelection.kt diff --git a/source/connect/connection-options.txt b/source/connect/connection-options.txt index 16be34bc..b84aa1bb 100644 --- a/source/connect/connection-options.txt +++ b/source/connect/connection-options.txt @@ -16,6 +16,7 @@ Specify Connection Options :maxdepth: 1 Network Compression + Server Selection Stable API Limit Server Execution Time Connection Pools diff --git a/source/connect/connection-options/server-selection.txt b/source/connect/connection-options/server-selection.txt new file mode 100644 index 00000000..5726fc4b --- /dev/null +++ b/source/connect/connection-options/server-selection.txt @@ -0,0 +1,145 @@ +.. _kotlin-sync-server-selection: + +========================== +Customize Server Selection +========================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: read preference, write, server selection + +Overview +-------- + +All MongoDB drivers follow a defined algorithm when selecting a server to read or write +from. By using the ``ClusterSettings`` property of a ``MongoClientSettings`` object, you can +customize this algorithm to choose the server that works best for your application. + +.. important:: + + Customizing the server selection algorithm might have unintended consequences, + such as degraded read or write performance. + +Server Selection Algorithm +-------------------------- + +When the {+driver-short+} executes a read operation, it performs the following steps, +in order, to select a MongoDB deployment: + +1. Selects all servers from the list of known servers suitable for the requested + operation, barring those that the driver considers unavailable or problematic + + 1. For reads, selects all servers that match the active read preference + + #. For writes, selects all writeable servers + +#. Calls the user-defined server-selector function, if the user provides one, and passes in + the list from the previous step + +#. Applies the ``localThreshold`` connection setting to the list of + servers returned from the function + +#. Selects at most two random servers from the list of servers that match the + preceding criteria, then selects the server with fewer outstanding concurrent operations + +When the {+driver-short+} executes a write operation, it begins by selecting all writeable +servers from the list of known servers, not just those that match the active read preference. +The remaining steps are identical to the preceding list. + +To learn more about the MongoDB server selection algorithm, see +:manual:`Server Selection Algorithm ` in the +{+mdb-server+} manual. + +Implement Custom Server Selection Logic +--------------------------------------- + +You can implement your own custom server selection logic by creating a class that +implements the ``ServerSelector`` interface. The following +example shows a simple custom server selection class that selects servers with a ``type`` +value of ``ServerType.REPLICA_SET_SECONDARY``: + +.. literalinclude:: /includes/connect/ServerSelection.kt + :language: kotlin + :copyable: true + :start-after: // start-custom-selector + :end-before: // end-custom-selector + +Use the ``applyToClusterSettings()`` method to pass an instance of this class to your +``MongoClientSettings``. The following example shows how to create +a ``MongoClient`` with an instance of the custom server selector class from the preceding example: + +.. literalinclude:: /includes/connect/ServerSelection.kt + :language: kotlin + :copyable: true + :start-after: // start-selector + :end-before: // end-selector + :dedent: + +Use Settings to Configure Server Selection +------------------------------------------ + +You can specify the following server selection settings in your ``MongoClient`` object or +in your connection URI: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Setting + - Description + + * - ``localThreshold`` + - | The latency window for server eligibility. If a server's round trip takes longer + | than the fastest server's round-trip time plus this value, the server isn't + | eligible for selection. You can specify this setting to a ``ClusterSettings`` object + in addition to the connection URI. + | + | **Data Type**: ``Integer`` + | **Default**: 15 milliseconds + | **Connection URI Example**: ``localThresholdMS=0`` + + * - ``readPreference`` + - | The client's default read-preference settings. For more information on read preference + options, see :manual:`Read Preference ` in the {+mdb-server+} manual. + You can specify this setting to a ``MongoClientSettings`` object in addition to the + connection URI. + | + | **Data Type**: `ReadPreference <{+core-api+}/ReadPreference.html>`__ + | **Default**: ``ReadPreference.primary()`` + | **Connection URI Example**: + + .. code-block:: none + :copyable: false + + readPreference=primaryPreferred + &maxStalenessSeconds=90 + &readPreferenceTags=dc:ny,rack:1 + + * - ``serverSelectionTimeout`` + - | The length of time the driver tries to select a server before timing out. + You can specify this setting to a ``ClusterSettings`` object in addition to the + connection URI. + | + | **Data Type**: ``Long`` + | **Default**: 30 seconds + | **Connection URI Example**: ``serverSelectionTimeoutMS=15000`` + +API Documentation +----------------- + +To learn more about the classes and methods used in this guide, see the following API +documentation: + +- `MongoClient <{+driver-api+}/-mongo-client/index.html>`__ +- `MongoClientSettings <{+core-api+}/MongoClientSettings.html>`__ +- `ServerSelector <{+core-api+}/selector/ServerSelector.html>`__ +- `ReadPreference <{+core-api+}/ReadPreference.html>`__ \ No newline at end of file diff --git a/source/includes/connect/ServerSelection.kt b/source/includes/connect/ServerSelection.kt new file mode 100644 index 00000000..c56313b0 --- /dev/null +++ b/source/includes/connect/ServerSelection.kt @@ -0,0 +1,31 @@ +package org.example +import com.mongodb.ConnectionString +import com.mongodb.MongoClientSettings +import com.mongodb.connection.ClusterDescription +import com.mongodb.connection.ServerDescription +import com.mongodb.connection.ServerType +import com.mongodb.kotlin.client.MongoClient +import com.mongodb.selector.ServerSelector + +// start-custom-selector +class CustomServerSelector : ServerSelector { + override fun select(cluster: ClusterDescription): List { + return cluster.serverDescriptions.filter { it.type == ServerType.REPLICA_SET_SECONDARY } + } +} +// end-custom-selector + +fun main() { + // start-selector + val settings = MongoClientSettings.builder() + .applyConnectionString(ConnectionString("")) + .applyToClusterSettings { builder -> + builder.serverSelector(CustomServerSelector()) + } + .build() + + val mongoClient = MongoClient.create(settings) + // end-selector +} + + From e7771dfe06c3a4ab06015ec3d4d2d99ffbef7413 Mon Sep 17 00:00:00 2001 From: Michael Morisi Date: Mon, 28 Jul 2025 09:24:02 -0400 Subject: [PATCH 20/22] DOCSP-51344: Logging (#115) --- snooty.toml | 2 + .../logging-and-monitoring/log4j2-gradle.rst | 6 + .../logging-and-monitoring/log4j2-maven.rst | 9 + .../logging-and-monitoring/logback-gradle.rst | 5 + .../logging-and-monitoring/logback-maven.rst | 9 + .../logging-and-monitoring/logging.rst | 6 + source/logging-and-monitoring.txt | 2 +- source/logging-and-monitoring/logging.txt | 401 +++++++++++++++++- 8 files changed, 438 insertions(+), 2 deletions(-) create mode 100644 source/includes/logging-and-monitoring/log4j2-gradle.rst create mode 100644 source/includes/logging-and-monitoring/log4j2-maven.rst create mode 100644 source/includes/logging-and-monitoring/logback-gradle.rst create mode 100644 source/includes/logging-and-monitoring/logback-maven.rst create mode 100644 source/includes/logging-and-monitoring/logging.rst diff --git a/snooty.toml b/snooty.toml index b69d414b..285611be 100644 --- a/snooty.toml +++ b/snooty.toml @@ -38,3 +38,5 @@ kotlin-docs = "https://kotlinlang.org" serialization-version = "1.6.0" kotlinx-dt-version = "0.6.1" mongocrypt-version = "{+full-version+}" +logbackVersion = "1.2.11" +log4j2Version = "2.17.1" diff --git a/source/includes/logging-and-monitoring/log4j2-gradle.rst b/source/includes/logging-and-monitoring/log4j2-gradle.rst new file mode 100644 index 00000000..525ee65b --- /dev/null +++ b/source/includes/logging-and-monitoring/log4j2-gradle.rst @@ -0,0 +1,6 @@ +.. code-block:: groovy + + dependencies { + implementation 'org.apache.logging.log4j:log4j-slf4j-impl:{+log4j2Version+}' + } + \ No newline at end of file diff --git a/source/includes/logging-and-monitoring/log4j2-maven.rst b/source/includes/logging-and-monitoring/log4j2-maven.rst new file mode 100644 index 00000000..a573f3c9 --- /dev/null +++ b/source/includes/logging-and-monitoring/log4j2-maven.rst @@ -0,0 +1,9 @@ +.. code-block:: xml + + + + org.apache.logging.log4j + log4j-slf4j-impl + {+log4j2Version+} + + diff --git a/source/includes/logging-and-monitoring/logback-gradle.rst b/source/includes/logging-and-monitoring/logback-gradle.rst new file mode 100644 index 00000000..2308da3e --- /dev/null +++ b/source/includes/logging-and-monitoring/logback-gradle.rst @@ -0,0 +1,5 @@ +.. code-block:: groovy + + dependencies { + implementation 'ch.qos.logback:logback-classic:{+logbackVersion+}' + } diff --git a/source/includes/logging-and-monitoring/logback-maven.rst b/source/includes/logging-and-monitoring/logback-maven.rst new file mode 100644 index 00000000..8e5737d3 --- /dev/null +++ b/source/includes/logging-and-monitoring/logback-maven.rst @@ -0,0 +1,9 @@ +.. code-block:: xml + + + + ch.qos.logback + logback-classic + {+logbackVersion+} + + diff --git a/source/includes/logging-and-monitoring/logging.rst b/source/includes/logging-and-monitoring/logging.rst new file mode 100644 index 00000000..f2658537 --- /dev/null +++ b/source/includes/logging-and-monitoring/logging.rst @@ -0,0 +1,6 @@ +.. code-block:: kotlin + + val mongoClient = MongoClient.create(); + val database = mongoClient.getDatabase(); + val collection = database.getCollection(); + collection.find().first(); diff --git a/source/logging-and-monitoring.txt b/source/logging-and-monitoring.txt index 4aa780f6..a2287066 100644 --- a/source/logging-and-monitoring.txt +++ b/source/logging-and-monitoring.txt @@ -13,8 +13,8 @@ Logging and Monitoring .. toctree:: - Monitoring Logging + Monitoring Change Streams Overview diff --git a/source/logging-and-monitoring/logging.txt b/source/logging-and-monitoring/logging.txt index ee9285ea..01b57477 100644 --- a/source/logging-and-monitoring/logging.txt +++ b/source/logging-and-monitoring/logging.txt @@ -8,4 +8,403 @@ Log Driver Events :local: :backlinks: none :depth: 2 - :class: singlecol \ No newline at end of file + :class: singlecol + +Overview +-------- + +In this guide, you can learn how to set up and configure a logger in the {+driver-short+}. + +This guide shows how to record events in the driver. If you want to learn how to +use information about the activity of the driver in code, see the :ref:`kotlin-sync-monitoring` +guide. + +Set Up a Logger +--------------- + +The {+driver-short+} uses Simple Logging Facade For Java (SLF4J) to allow you to specify +your logging framework of choice. For more information about SLF4J, see the `SLF4J documentation +`__. + +Setting up a logger is optional. To set up a logger, you must include the following in +your project: + +- The ``slf4j-api`` artifact in your classpath +- A logging framework +- A **binding** that connects the ``slf4j-api`` artifact to a logging framework + +If the driver can't find the ``slf4j-api`` artifact in your classpath, the driver outputs +the following warning and disables all further logging: + +.. code-block:: + + WARNING: SLF4J not found on the classpath. Logging is disabled for the 'org.mongodb.driver' component + +Logger Setup Example +~~~~~~~~~~~~~~~~~~~~ + +The following example shows how to set up a logger. Select the :guilabel:`Logback` or +:guilabel:`Log4j2` tab to see the corresponding syntax: + +.. tabs:: + + .. tab:: Logback + :tabid: Logback-binding + + Select the :guilabel:`Maven` or :guilabel:`Gradle` tab to learn about how to set up + Logback with your project's dependency management tool: + + .. tabs:: + + .. tab:: Maven + :tabid: maven + + Add the following dependency to your ``pom.xml`` file. + + .. include:: /includes/logging-and-monitoring/logback-maven.rst + + .. tab:: Gradle + :tabid: gradle + + Add the following dependency to your ``build.gradle`` file. + + .. include:: /includes/logging-and-monitoring/logback-gradle.rst + + Once you have included the preceding dependency, connect to your + MongoDB instance and retrieve a document with the following code: + + .. include:: /includes/logging-and-monitoring/logging.rst + + The preceding code will ouput a message that resembles the following: + + .. code-block:: none + :copyable: false + + ... + 12:14:55.833 [main] DEBUG org.mongodb.driver.connection - Checkout started for connection to + 12:14:55.834 [main] DEBUG org.mongodb.driver.connection - Connection created: address=, driver-generated ID=3 + 12:14:55.836 [main] DEBUG org.mongodb.driver.connection - Connection ready: address=, driver-generated ID=3, established in=4 ms + 12:14:55.843 [main] DEBUG org.mongodb.driver.connection - Connection checked out: address=, driver-generated ID=3, duration=9 ms + + .. note:: Default Log Level + + The default log level of Logback is DEBUG. To learn how to change your + Logback logger's log level, see the + :ref:`Configure Log Level ` section of this page. + + .. tab:: Log4j2 + :tabid: Log4j2-binding + + Select the :guilabel:`Maven` or :guilabel:`Gradle` tab to learn about how to set up + Log4j2 with your project's dependency management tool. + + .. tabs:: + + .. tab:: Maven + :tabid: maven + + Add the following dependency to your ``pom.xml`` file. + + .. include:: /includes/logging-and-monitoring/log4j2-maven.rst + + .. tab:: Gradle + :tabid: gradle + + Add the following dependency to your ``build.gradle`` file. + + .. include:: /includes/logging-and-monitoring/log4j2-gradle.rst + + Once you have included the preceding dependency, log an error by using the + following code: + + .. code-block:: kotlin + + import org.slf4j.Logger; + import org.slf4j.LoggerFactory; + + ... + + val logger = LoggerFactory.getLogger("MyApp"); + logger.error("Logging an Error"); + + The preceding code will ouput a message that resembles the following: + + .. code-block:: none + :copyable: false + + 12:35:00.438 [main] ERROR - Logging an Error + + .. note:: Default Log Level + + The default log level of Log4J2 is ERROR. This means that running + standard operations in the {+driver-short+} will not produce output + from Log4J2 without configuration. To learn how to change your Log4J2 + logger's log level, see the + :ref:`Configure Log Level ` section of this page. + +.. _kotlin-sync-configure-log-level: + +Configure Log Level +------------------- + +You can configure the log level of your logger by using the configuration system of the logging +framework bound to SLF4J. The log level specifies a lower bound for how urgent a message +must be for the logger to output that message. + +Logger Configuration Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example configures the log level to ``INFO``. Select the :guilabel:`Logback` or +:guilabel:`Log4j2` tab to see the corresponding syntax: + +.. tabs:: + + .. tab:: Logback + :tabid: Logback-binding + + Specify Logback configurations in a file named ``logback.xml``. + You must be able to access this file from your classpath. + + The Logback framework defines the following log levels ordered from most urgent to + least urgent: + + - ``ERROR`` + - ``WARN`` + - ``INFO`` + - ``DEBUG`` + - ``TRACE`` + + Set your ``logback.xml`` file to the following: + + .. code-block:: xml + + + + + + %-4relative [%thread] %-5level %logger{30} - %msg%n + + + + + + + + + To test that your logger configuration was successful, run the following + code: + + .. include:: /includes/logging-and-monitoring/logging.rst + + This code produces output that resembles the following: + + .. code-block:: none + :copyable: false + + ... + 317 [main] INFO org.mongodb.driver.client - MongoClient with metadata {"driver": {"name": "", "version": ""}, "os": {"type": "", "name": "", "architecture": "", "version": ""}, "platform": ""} created with settings + 345 [cluster-ClusterId{value='', description='null'}-] INFO org.mongodb.driver.cluster - Monitor thread successfully connected to server with description ServerDescription{address=, type=, cryptd=false, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=, minRoundTripTimeNanos= + + + + + + + + + + + + + + To test that your logger configuration was successful, run the following + code: + + .. include:: /includes/logging-and-monitoring/logging.rst + + This code produces output that resembles the following: + + .. code-block:: none + :copyable: false + + ... + 21:19:25.696 [main] INFO org.mongodb.driver.client - MongoClient with metadata {"driver": {"name": "", "version": ""}, "os": {"type": "", "name": "", "architecture": "", "version": ""}, "platform": ""} created with settings + 21:19:25.710 [cluster-ClusterId{value='', description='null'}-] INFO org.mongodb.driver.cluster - Monitor thread successfully connected to server with description ServerDescription{address=, type=, cryptd=false, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=, minRoundTripTimeNanos= + + + + %-4relative [%thread] %-5level %logger{30} - %msg%n + + + + + + + + + + To test that your logger configuration was successful, run the following + code. + + .. include:: /includes/logging-and-monitoring/logging.rst + + This code produces output that resembles the following. + + .. code-block:: none + :copyable: false + + ... + 255 [main] DEBUG org.mongodb.driver.connection - Connection pool created for using options + 301 [cluster-ClusterId{value='', description='null'}-] DEBUG org.mongodb.driver.connection - Connection pool ready for + 321 [main] DEBUG org.mongodb.driver.connection - Checkout started for connection to + 323 [main] DEBUG org.mongodb.driver.connection - Connection created: address=, driver-generated ID=3 + 335 [main] DEBUG org.mongodb.driver.connection - Connection ready: address=, driver-generated ID=3, established in= ms + 336 [main] DEBUG org.mongodb.driver.connection - Connection checked out: address=, driver-generated ID=3, duration= ms + 363 [main] DEBUG org.mongodb.driver.connection - Connection checked in: address=, driver-generated ID=3 + + .. tab:: Log4j2 + :tabid: Log4j2-binding + + Set your ``log4j2.xml`` file to the following: + + .. code-block:: xml + :emphasize-lines: 9 + + + + + + + + + + + + + + + + + To test that your logger configuration was successful, run the following + code. + + .. include:: /includes/logging-and-monitoring/logging.rst + + This code produces output that resembles the following: + + .. code-block:: none + :copyable: false + + ... + 21:27:17.035 [main] DEBUG org.mongodb.driver.connection - Connection pool created for using options + 21:27:17.058 [cluster-ClusterId{value='', description='null'}-] DEBUG org.mongodb.driver.connection - Connection pool ready for + 21:27:17.064 [main] DEBUG org.mongodb.driver.connection - Checkout started for connection to + 21:27:17.069 [main] DEBUG org.mongodb.driver.connection - Connection created: address=, driver-generated ID=3 + 21:27:17.075 [main] DEBUG org.mongodb.driver.connection - Connection ready: address=, driver-generated ID=3, established in= ms + 21:27:17.075 [main] DEBUG org.mongodb.driver.connection - Connection checked out: address=, driver-generated ID=3, duration= ms + 21:27:17.086 [main] DEBUG org.mongodb.driver.connection - Connection checked in: address=, driver-generated ID=3 + +Additional Information +---------------------- + +To learn more about MongoDB's logging capabilities, see :manual:`Log Messages ` in the {+mdb-server+} +manual. + +For complete information about the logging frameworks discussed in this guide, see the +following external documentation: + +- `SLF4J documentation `__ +- `Logback documentation `__ +- `Log4j2 documentation `__ + From cf2870db0848e2f677893d7486d15709cf4711c6 Mon Sep 17 00:00:00 2001 From: shuangela Date: Mon, 28 Jul 2025 10:34:40 -0400 Subject: [PATCH 21/22] DOCSP-51889-retryable-reads-and-writes (#126) * add retryable section * mb feedback --- source/crud/configure.txt | 42 ++++++++++++++++++++++++++++--- source/includes/configure-crud.kt | 17 +++++++++++++ 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/source/crud/configure.txt b/source/crud/configure.txt index 175dd382..fc60312b 100644 --- a/source/crud/configure.txt +++ b/source/crud/configure.txt @@ -307,17 +307,16 @@ tab to see corresponding code for each approach: :tabid: settings .. literalinclude:: /includes/configure-crud.kt - :language: rust + :language: kotlin :dedent: :start-after: start-local-threshold-settings :end-before: end-local-threshold-settings - .. tab:: Connection URI :tabid: uri .. literalinclude:: /includes/configure-crud.kt - :language: rust + :language: kotlin :dedent: :start-after: start-local-threshold-uri :end-before: end-local-threshold-uri @@ -325,6 +324,43 @@ tab to see corresponding code for each approach: In the preceding example, the {+driver-short+} distributes reads among matching members within 35 milliseconds of the closest member's ping time. +Retryable Reads and Writes +-------------------------- + +The {+driver-short+} automatically retries certain read and write operations a single time +if they fail due to a network or server error. + +You can explicitly disable retryable reads or retryable writes by setting the ``retryReads`` or +``retryWrites`` option to ``false`` in a ``MongoClientSettings`` instance. You can also +set the ``retryReads`` or ``retryWrites`` options in your connection URI. + +The following example sets both retryable reads and retryable writes to ``false``. Select the :guilabel:`MongoClientSettings` or :guilabel:`Connection URI` +tab to see corresponding code for each approach: + +.. tabs:: + + .. tab:: MongoClientSettings + :tabid: settings + + .. literalinclude:: /includes/configure-crud.kt + :language: kotlin + :dedent: + :start-after: start-retryable-reads-writes + :end-before: end-retryable-reads-writes + + .. tab:: Connection URI + :tabid: uri + + .. literalinclude:: /includes/configure-crud.kt + :language: kotlin + :dedent: + :start-after: start-retryable-reads-writes-uri + :end-before: end-retryable-reads-writes-uri + +To learn more about supported retryable read operations, see :manual:`Retryable Reads ` +in the {+mdb-server+} manual. To learn more about supported retryable write +operations, see :manual:`Retryable Writes ` in the {+mdb-server+} manual. + API Documentation ----------------- diff --git a/source/includes/configure-crud.kt b/source/includes/configure-crud.kt index 3d5150dd..73216b18 100644 --- a/source/includes/configure-crud.kt +++ b/source/includes/configure-crud.kt @@ -106,6 +106,23 @@ fun main() { val latencyClient2 = MongoClient.create(latencySettings) // end-local-threshold-settings + // Disable retryable reads and writes using MongoClientSettings builder + // start-retryable-reads-writes + val retrySettings = MongoClientSettings.builder() + .applyConnectionString(ConnectionString("mongodb://localhost:27017/")) + .retryReads(false) // Disables automatic retries of read operations + .retryWrites(false) // Disables automatic retries of write operations + .build() + + val retryClient = MongoClient.create(retrySettings) + + // end-retryable-reads-writes + + // start-retryable-reads-writes-uri + val retryUri = "mongodb://localhost:27017/?retryReads=false&retryWrites=false" + val retryUriClient = MongoClient.create(retryUri) + // end-retryable-reads-writes-uri + // Close the MongoClient connection mongoClient.close() } From 6c85c3bc51df169aa915fc735d1b6726c29cfad4 Mon Sep 17 00:00:00 2001 From: Nora Reidy Date: Tue, 29 Jul 2025 13:37:18 -0400 Subject: [PATCH 22/22] DOCSP-51325: Connection pools (#119) * DOCSP-51325: Connection pools * edits * edits * keywords * link * imports * code edit * move file --- source/connect/connection-options.txt | 2 +- .../connection-options/connection-pools.txt | 221 ++++++++++++++++++ source/connect/connection-pools.txt | 16 -- source/includes/connect/connection-pools.kt | 21 ++ 4 files changed, 243 insertions(+), 17 deletions(-) create mode 100644 source/connect/connection-options/connection-pools.txt delete mode 100644 source/connect/connection-pools.txt create mode 100644 source/includes/connect/connection-pools.kt diff --git a/source/connect/connection-options.txt b/source/connect/connection-options.txt index b84aa1bb..3357df9a 100644 --- a/source/connect/connection-options.txt +++ b/source/connect/connection-options.txt @@ -19,7 +19,7 @@ Specify Connection Options Server Selection Stable API Limit Server Execution Time - Connection Pools + Connection Pools Overview -------- diff --git a/source/connect/connection-options/connection-pools.txt b/source/connect/connection-options/connection-pools.txt new file mode 100644 index 00000000..16d266aa --- /dev/null +++ b/source/connect/connection-options/connection-pools.txt @@ -0,0 +1,221 @@ +.. _kotlin-sync-connection-pools: + +================ +Connection Pools +================ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: concurrent, request, kotlin + +Overview +-------- + +In this guide, you can learn about how the {+driver-short+} uses connection pools to manage +connections to a MongoDB deployment. You can specify connection pool settings +in your application to configure this behavior. + +A connection pool is a cache of open database connections maintained by the {+driver-short+}. +When your application requests a connection to MongoDB, the driver retrieves +a connection from the pool, performs operations, and returns the connection +to the pool for reuse. + +Connection pools help reduce application latency and the number of times the driver +creates new connections. + +Create a Connection Pool +------------------------ + +Each ``MongoClient`` instance has a built-in connection pool for each server in your +MongoDB topology. If you do not configure the ``minPoolSize`` option, connection +pools open sockets on demand. These sockets support concurrent MongoDB +operations in your application. + +When you instantiate a new ``MongoClient``, the client opens two sockets per server +in your MongoDB topology to monitor the server's state. + +For example, a client connected to a three-node replica set opens six monitoring +sockets. If the application uses the default setting for ``maxPoolSize`` and +only queries the primary node, there can be at most ``106`` open +sockets and ``100`` connections in the connection pool. If the application uses +a :ref:`read preference ` to query the secondary nodes, there +can be ``306`` total connections. + +For efficiency, create a client once for each process and reuse it for all +operations. Avoid creating a new client for each request because this will +increase latency. + +Configure a Connection Pool +--------------------------- + +You can specify settings for your connection pool by using either a connection +string or a ``MongoClientSettings`` object. + +Select the :guilabel:`Connection String` or :guilabel:`MongoClientSettings` tab to +see the corresponding syntax: + +.. tabs:: + + .. tab:: Connection String + :tabid: uri + + The following table describes connection pool options that you can set + in your connection string: + + .. list-table:: + :widths: 25,75 + :header-rows: 1 + + * - Option + - Description + + * - ``maxConnecting`` + + - Sets the maximum number of connections a pool may establish + concurrently. + + *Default:* ``2`` + + * - ``maxIdleTimeMS`` + + - Sets the maximum number of milliseconds that a connection can + remain idle in the pool before it is removed and closed. + + *Default:* ``0`` + + * - ``maxPoolSize`` + + - Sets the maximum number of connections that can be open in a pool. If an + operation needs a new connection while the connection pool has + the maximum number of open connections, the operation + waits for a new connection to open. To limit this + waiting time, use the single timeout setting. To learn more, + see the :ref:`kotlin-sync-csot` guide. + + *Default:* ``100`` + + * - ``minPoolSize`` + + - Sets the minimum number of connections that can be open in a pool. + The value of ``minPoolSize`` must be less than + the value of ``maxPoolSize``. + + *Default*: ``0`` + + * - ``maxLifeTimeMS`` + + - Sets the maximum amount of time, in milliseconds, the driver + can continue to use a pooled connection before closing the + connection. A value of ``0`` indicates that there is no upper bound on + how long the driver can keep a pooled connection open. + + *Default*: ``0`` + + To learn more about these options, see the `ConnectionString + <{+core-api+}/ConnectionString.html>`__ API documentation. + + .. tab:: MongoClientSettings + :tabid: MongoClient + + To specify connection pool settings in a ``MongoClientSettings`` object, + chain the ``applyToConnectionPoolSettings()`` method to the ``MongoClientSettings`` builder. + Pass a ``ConnectionPoolSettings.Builder`` block as a parameter to the + ``applyToConnectionPoolSettings()`` method. + + The following table describes the setter methods you can use in a + ``ConnectionPoolSettings.Builder`` block to configure the connection pool: + + .. list-table:: + :widths: 40 60 + :header-rows: 1 + + * - Method + - Description + + * - ``addConnectionPoolListener()`` + - Adds a listener for connection pool-related events. + + * - ``applyConnectionString()`` + - Applies the settings from a ``ConnectionString`` object. + + * - ``applySettings()`` + - Uses the connection pool settings specified in a + ``ConnectionPoolSettings`` object. + + * - ``maintenanceFrequency()`` + - Sets the frequency for running connection pool maintenance jobs. + + * - ``maintenanceInitialDelay()`` + - Sets the time to wait before running the first maintenance job + on the connection pool. + + * - ``maxConnectionIdleTime()`` + - Sets the maximum time a connection can be idle before it's closed. + + * - ``maxConnectionLifeTime()`` + - Sets the maximum time a pooled connection can be open before it's + closed. + + * - ``maxSize()`` + - Sets the maximum number of connections that can be open in a pool. + + *Default*: ``100`` + + * - ``maxWaitTime()`` + - Sets the maximum time to wait for an available connection. + + *Default*: ``2`` minutes + + * - ``minSize()`` + - Sets the minimum number of connections that can be open in a pool. + + *Default*: ``0`` + + To learn more about these methods, see the `ConnectionPoolSettings.Builder + <{+core-api+}/connection/ConnectionPoolSettings.Builder.html>`__ + API documentation. + +Example +~~~~~~~ + +The following example shows how to create a connection pool that +has maximum size of ``50`` connections. + +Select the :guilabel:`Connection String` or :guilabel:`MongoClientSettings` tab to +see the corresponding syntax: + +.. tabs:: + + .. tab:: Connection String + :tabid: uri + + .. literalinclude:: /includes/connect/connection-pools.kt + :start-after: start-uri-option + :end-before: end-uri-option + :language: kotlin + :dedent: + + .. tab:: MongoClientSettings + :tabid: MongoClient + + .. literalinclude:: /includes/connect/connection-pools.kt + :start-after: start-client-settings + :end-before: end-client-settings + :language: kotlin + :dedent: + +Additional Information +---------------------- + +To learn more about using a connection pool, see +:manual:`Connection Pool Overview ` +in the {+mdb-server+} manual. diff --git a/source/connect/connection-pools.txt b/source/connect/connection-pools.txt deleted file mode 100644 index e8b95f19..00000000 --- a/source/connect/connection-pools.txt +++ /dev/null @@ -1,16 +0,0 @@ -.. _kotlin-sync-connection-pools: - -================ -Connection Pools -================ - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - - -.. _kotlin-sync-connection-pool-settings: - -.. TODO \ No newline at end of file diff --git a/source/includes/connect/connection-pools.kt b/source/includes/connect/connection-pools.kt new file mode 100644 index 00000000..b1534181 --- /dev/null +++ b/source/includes/connect/connection-pools.kt @@ -0,0 +1,21 @@ +import com.mongodb.ConnectionString +import com.mongodb.kotlin.client.MongoClient +import com.mongodb.MongoClientSettings + +fun main() { + // start-uri-option + val uri = "mongodb://:/?maxPoolSize=50" + val client = MongoClient.create(uri) + // end-uri-option + + // start-client-settings + val mongoClient = MongoClient.create( + MongoClientSettings.builder() + .applyConnectionString(ConnectionString("mongodb://:/")) + .applyToConnectionPoolSettings { builder -> + builder.maxSize(50) + } + .build() + ) + // end-client-settings +} \ No newline at end of file