From c407f2378e322e24c3f4e1e9beba74348fd65ce3 Mon Sep 17 00:00:00 2001 From: Stephanie <52582720+stephmarie17@users.noreply.github.com> Date: Mon, 17 Mar 2025 13:27:09 -0700 Subject: [PATCH 1/4] DOCSP-48375 ToC reorg part one (#1035) --- config/redirects | 61 +++- snooty.toml | 19 +- source/aggregation-tutorials.txt | 124 ------- source/{fundamentals => }/aggregation.txt | 115 ++++++- .../filtered-subset.txt | 0 .../group-total.txt | 0 .../multi-field-join.txt | 0 .../one-to-one-join.txt | 0 .../unpack-arrays.txt | 0 .../collations.txt | 3 +- .../quick-start/connect-to-mongodb.txt | 0 .../create-a-connection-string.txt | 0 .../quick-start/create-a-deployment.txt | 0 .../quick-start/download-and-install.txt | 0 .../quick-start/facets.toml | 0 .../quick-start/next-steps.txt | 0 .../connection.txt => connect.txt} | 42 +-- .../connection-options.txt | 16 +- .../connection-options/connection-pools.txt | 30 ++ .../connection-options}/csot.txt | 0 .../network-compression.txt | 0 .../connection-options/server-selection.txt | 21 ++ .../connection-options}/stable-api.txt | 0 source/connect/connection-targets.txt | 18 + .../connection-troubleshooting.txt | 0 .../connect.txt => connect/mongoclient.txt} | 12 +- source/crud.txt | 38 +++ .../bulk.txt => crud/bulk-write.txt} | 2 +- .../crud/compound-operations.txt | 0 source/crud/configure.txt | 321 ++++++++++++++++++ .../crud/write-operations => crud}/delete.txt | 1 + source/{fundamentals => crud}/gridfs.txt | 2 +- .../crud/write-operations => crud}/insert.txt | 1 + .../write-operations => crud}/pkFactory.txt | 0 source/crud/query.txt | 253 ++++++++++++++ .../{usage-examples => crud/query}/count.txt | 1 + .../read-operations => crud/query}/cursor.txt | 1 + .../query}/distinct.txt | 1 + .../read-operations => crud/query}/geo.txt | 3 +- .../query}/project.txt | 1 + .../crud => crud/query}/query-document.txt | 1 + .../query}/retrieve.txt | 11 +- .../query/specify-documents-to-return.txt | 28 ++ .../read-operations => crud/query}/text.txt | 1 + .../crud/read-write-pref.txt | 0 .../{fundamentals => crud}/transactions.txt | 1 + .../upsert.txt => crud/update.txt} | 15 +- .../update}/embedded-arrays.txt | 1 + .../update}/modify.txt | 12 +- source/crud/update/replace.txt | 21 ++ source/data-formats.txt | 35 ++ source/data-formats/bson.txt | 25 ++ .../time-series.txt | 4 +- source/fundamentals/bson.txt | 31 -- source/fundamentals/crud.txt | 57 ---- source/fundamentals/crud/read-operations.txt | 38 --- source/fundamentals/crud/write-operations.txt | 1 - source/get-started.txt | 229 +++++++++++++ source/index.txt | 117 +++---- source/{fundamentals => }/indexes.txt | 3 +- source/monitoring-and-logging.txt | 24 ++ .../change-streams.txt} | 28 +- .../logging.txt | 0 .../monitoring.txt | 2 + source/quick-start.txt | 45 --- source/reference.txt | 14 + source/{ => reference}/compatibility.txt | 0 source/{ => reference}/quick-reference.txt | 2 +- .../release-notes.txt} | 7 +- source/{ => reference}/upgrade.txt | 0 source/{fundamentals => }/run-command.txt | 0 source/security.txt | 34 ++ .../authentication.txt | 9 +- .../authentication/enterprise-mechanisms.txt | 0 .../authentication/mechanisms.txt | 0 .../encrypt-fields.txt | 0 .../connection => security}/socks.txt | 1 + .../connection => security}/tls.txt | 1 + source/{fundamentals => }/typescript.txt | 5 +- source/usage-examples.txt | 7 +- 80 files changed, 1464 insertions(+), 432 deletions(-) delete mode 100644 source/aggregation-tutorials.txt rename source/{fundamentals => }/aggregation.txt (56%) rename source/{aggregation-tutorials => aggregation}/filtered-subset.txt (100%) rename source/{aggregation-tutorials => aggregation}/group-total.txt (100%) rename source/{aggregation-tutorials => aggregation}/multi-field-join.txt (100%) rename source/{aggregation-tutorials => aggregation}/one-to-one-join.txt (100%) rename source/{aggregation-tutorials => aggregation}/unpack-arrays.txt (100%) rename source/{fundamentals => archive-reference-files}/collations.txt (99%) rename source/{ => archive-reference-files}/quick-start/connect-to-mongodb.txt (100%) rename source/{ => archive-reference-files}/quick-start/create-a-connection-string.txt (100%) rename source/{ => archive-reference-files}/quick-start/create-a-deployment.txt (100%) rename source/{ => archive-reference-files}/quick-start/download-and-install.txt (100%) rename source/{ => archive-reference-files}/quick-start/facets.toml (100%) rename source/{ => archive-reference-files}/quick-start/next-steps.txt (100%) rename source/{fundamentals/connection.txt => connect.txt} (65%) rename source/{fundamentals/connection => connect}/connection-options.txt (96%) create mode 100644 source/connect/connection-options/connection-pools.txt rename source/{fundamentals/connection => connect/connection-options}/csot.txt (100%) rename source/{fundamentals/connection => connect/connection-options}/network-compression.txt (100%) create mode 100644 source/connect/connection-options/server-selection.txt rename source/{fundamentals => connect/connection-options}/stable-api.txt (100%) create mode 100644 source/connect/connection-targets.txt rename source/{ => connect}/connection-troubleshooting.txt (100%) rename source/{fundamentals/connection/connect.txt => connect/mongoclient.txt} (95%) create mode 100644 source/crud.txt rename source/{fundamentals/crud/write-operations/bulk.txt => crud/bulk-write.txt} (99%) rename source/{fundamentals => }/crud/compound-operations.txt (100%) create mode 100644 source/crud/configure.txt rename source/{fundamentals/crud/write-operations => crud}/delete.txt (99%) rename source/{fundamentals => crud}/gridfs.txt (99%) rename source/{fundamentals/crud/write-operations => crud}/insert.txt (99%) rename source/{fundamentals/crud/write-operations => crud}/pkFactory.txt (100%) create mode 100644 source/crud/query.txt rename source/{usage-examples => crud/query}/count.txt (99%) rename source/{fundamentals/crud/read-operations => crud/query}/cursor.txt (99%) rename source/{fundamentals/crud/read-operations => crud/query}/distinct.txt (99%) rename source/{fundamentals/crud/read-operations => crud/query}/geo.txt (98%) rename source/{fundamentals/crud/read-operations => crud/query}/project.txt (99%) rename source/{fundamentals/crud => crud/query}/query-document.txt (99%) rename source/{fundamentals/crud/read-operations => crud/query}/retrieve.txt (98%) create mode 100644 source/crud/query/specify-documents-to-return.txt rename source/{fundamentals/crud/read-operations => crud/query}/text.txt (99%) rename source/{fundamentals => }/crud/read-write-pref.txt (100%) rename source/{fundamentals => crud}/transactions.txt (99%) rename source/{fundamentals/crud/write-operations/upsert.txt => crud/update.txt} (93%) rename source/{fundamentals/crud/write-operations => crud/update}/embedded-arrays.txt (99%) rename source/{fundamentals/crud/write-operations => crud/update}/modify.txt (95%) create mode 100644 source/crud/update/replace.txt create mode 100644 source/data-formats.txt create mode 100644 source/data-formats/bson.txt rename source/{fundamentals => data-formats}/time-series.txt (95%) delete mode 100644 source/fundamentals/bson.txt delete mode 100644 source/fundamentals/crud.txt delete mode 100644 source/fundamentals/crud/read-operations.txt create mode 100644 source/get-started.txt rename source/{fundamentals => }/indexes.txt (99%) create mode 100644 source/monitoring-and-logging.txt rename source/{usage-examples/changeStream.txt => monitoring-and-logging/change-streams.txt} (93%) rename source/{fundamentals => monitoring-and-logging}/logging.txt (100%) rename source/{fundamentals => monitoring-and-logging}/monitoring.txt (97%) delete mode 100644 source/quick-start.txt create mode 100644 source/reference.txt rename source/{ => reference}/compatibility.txt (100%) rename source/{ => reference}/quick-reference.txt (99%) rename source/{whats-new.txt => reference/release-notes.txt} (99%) rename source/{ => reference}/upgrade.txt (100%) rename source/{fundamentals => }/run-command.txt (100%) create mode 100644 source/security.txt rename source/{fundamentals => security}/authentication.txt (76%) rename source/{fundamentals => security}/authentication/enterprise-mechanisms.txt (100%) rename source/{fundamentals => security}/authentication/mechanisms.txt (100%) rename source/{fundamentals => security}/encrypt-fields.txt (100%) rename source/{fundamentals/connection => security}/socks.txt (99%) rename source/{fundamentals/connection => security}/tls.txt (99%) rename source/{fundamentals => }/typescript.txt (99%) diff --git a/config/redirects b/config/redirects index 5119e2f69..73b0fb329 100644 --- a/config/redirects +++ b/config/redirects @@ -23,4 +23,63 @@ raw: ${prefix}/stable -> ${base}/current/ [*-v5.5]: ${prefix}/${version}/fundamentals/run-command/ -> ${base}/${version}/usage-examples/command/ [*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/change-a-document/ -> ${base}/${version}/fundamentals/crud/write-operations/modify/ -[*-v6.0): ${prefix}/${version}/fundamentals/connection/socks/ -> ${base}/${version}/ +[*-v6.0)]: ${prefix}/${version}/fundamentals/connection/socks/ -> ${base}/${version}/ + +[*-master]: ${prefix}/${version}/quick-start/download-and-install/ -> ${base}/${version}/get-started/ +[*-master]: ${prefix}/${version}/quick-start/create-a-deployment/ -> ${base}/${version}/get-started/ +[*-master]: ${prefix}/${version}/quick-start/create-a-connection-string/ -> ${base}/${version}/get-started/ +[*-master]: ${prefix}/${version}/quick-start/connect-to-mongodb/ -> ${base}/${version}/get-started/ +[*-master]: ${prefix}/${version}/quick-start/next-steps/ -> ${base}/${version}/get-started/ +[*-master]: ${prefix}/${version}/fundamentals/connection/ -> ${base}/${version}/connect/ +[*-master]: ${prefix}/${version}/fundamentals/connection/connect/ -> ${base}/${version}/connect/mongoclient/ +[*-master]: ${prefix}/${version}/fundamentals/connection/connection-options/ -> ${base}/${version}/connect/connection-options/ +[*-master]: ${prefix}/${version}/connection-troubleshooting/ -> ${base}/${version}/connect/connection-troubleshooting/ +[*-master]: ${prefix}/${version}/fundamentals/connection/network-compression/ -> ${base}/${version}/connect/connection-options/network-compression/ +[*-master]: ${prefix}/${version}/fundamentals/connection/csot/ -> ${base}/${version}/connect/connection-options/csot/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/bulk/ -> ${base}/${version}/crud/bulk-write/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/insert/ -> ${base}/${version}/crud/insert/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/upsert/ -> ${base}/${version}/crud/update/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/delete/ -> ${base}/${version}/crud/delete/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/ -> ${base}/${version}/crud/query/ +[*-master]: ${prefix}/${version}/fundamentals/crud/query-document/ -> ${base}/${version}/crud/query/query-document/ +[*-master]: ${prefix}/${version}/fundamentals/crud/compound-operations/ -> ${base}/${version}/crud/compound-operations/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-write-pref/ -> ${base}/${version}/crud/read-write-pref/ +[*-master]: ${prefix}/${version}/fundamentals/transactions/ -> ${base}/${version}/crud/transactions/ +[*-master]: ${prefix}/${version}/fundamentals/gridfs/ -> ${base}/${version}/crud/gridfs/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/retrieve/ -> ${base}/${version}/crud/query/retrieve/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/project/ -> ${base}/${version}/crud/query/project/ +[*-master]: ${prefix}/${version}/fundamentals/usage-examples/count/ -> ${base}/${version}/crud/query/count/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/distinct/ -> ${base}/${version}/crud/query/distinct/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/cursor/ -> ${base}/${version}/crud/query/cursor/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/geo/ -> ${base}/${version}/crud/query/geo/ +[*-master]: ${prefix}/${version}/fundamentals/crud/time-series/ -> ${base}/${version}/data-formats/time-series/ +[*-master]: ${prefix}/${version}/fundamentals/bson/ -> ${base}/${version}/data-formats/bson/ +[*-master]: ${prefix}/${version}/fundamentals/indexes/ -> ${base}/${version}/indexes/ +[*-master]: ${prefix}/${version}/fundamentals/run-command/ -> ${base}/${version}/run-command/ +[*-master]: ${prefix}/${version}/fundamentals/monitoring/ -> ${base}/${version}/monitoring-and-logging/monitoring/ +[*-master]: ${prefix}/${version}/fundamentals/logging/ -> ${base}/${version}/monitoring-and-logging/logging/ +[*-master]: ${prefix}/${version}/usage-examples/changeStream -> ${base}/monitoring-and-logging/change-streams/ +[*-master]: ${prefix}/${version}/fundamentals/aggregation/ -> ${base}/${version}/aggregation/ +[*-master]: ${prefix}/${version}/aggregation-tutorials/ -> ${base}/aggregation/ +[*-master]: ${prefix}/${version}/aggregation-tutorials/filtered-subset/ -> ${base}/aggregation/filtered-subset/ +[*-master]: ${prefix}/${version}/aggregation-tutorials/group-total/ -> ${base}/aggregation/group-total/ +[*-master]: ${prefix}/${version}/aggregation-tutorials/multi-field-join/ -> ${base}/aggregation/multi-field-join/ +[*-master]: ${prefix}/${version}/aggregation-tutorials/one-to-one-join/ -> ${base}/aggregation/one-to-one-join/ +[*-master]: ${prefix}/${version}/aggregation-tutorials/unpack-arrays/ -> ${base}/aggregation/unpack-arrays/ +[*-master]: ${prefix}/${version}/fundamentals/authentication -> ${base}/security/authentication/ +[*-master]: ${prefix}/${version}/fundamentals/authentication/mechanisms/ -> ${base}/security/authentication/mechanisms/ +[*-master]: ${prefix}/${version}/fundamentals/authentication/enterprise-mechanisms/ -> ${base}/security/authentication/enterprise-mechanisms/ +[*-master]: ${prefix}/${version}/fundamentals/encrypt-fields/ -> ${base}/security/encrypt-fields/ +[*-master]: ${prefix}/${version}/fundamentals/connection/tls/ -> ${base}/security/tls/ +[*-master]: ${prefix}/${version}/fundamentals/connection/socks/ -> ${base}/security/socks/ +[*-master]: ${prefix}/${version}/fundamentals/typescript/ -> ${base}/typescript/ +[*-master]: ${prefix}/${version}/whats-new/ -> ${base}/reference/release-notes/ +[*-master]: ${prefix}/${version}/compatibility/ -> ${base}/reference/compatibility/ +[*-master]: ${prefix}/${version}/upgrade/ -> ${base}/reference/upgrade/ +[*-master]: ${prefix}/${version}/quick-reference/ -> ${base}/reference/quick-reference/ +[*-master]: ${prefix}/${version}/fundamentals/collations/ -> ${base}/crud/configure/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/text/ -> ${base}/crud/query/text/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/modify/ -> ${base}/crud/update/modify/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/embedded-arrays/ -> ${base}/crud/update/embedded-arrays/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/pkFactory/ -> ${base}/crud/pkFactory/ + diff --git a/snooty.toml b/snooty.toml index 57178bd89..4789d56ae 100644 --- a/snooty.toml +++ b/snooty.toml @@ -7,14 +7,19 @@ intersphinx = [ ] toc_landing_pages = [ - "/fundamentals/authentication", - "/fundamentals", - "/fundamentals/connection", - "/fundamentals/crud", - "/fundamentals/bson", - "/usage-examples", - "/quick-start", + "/get-started", + "/connect", + "/aggregation", + "/aggregation/aggregation-tutorials", + "/security", + "/security/authentication", "/aggregation-tutorials", + "/data-formats", + "connect/connection-options", + "crud", + "/crud/query", + "crud/update", + "monitoring-and-logging" ] sharedinclude_root = "https://raw.githubusercontent.com/10gen/docs-shared/main/" diff --git a/source/aggregation-tutorials.txt b/source/aggregation-tutorials.txt deleted file mode 100644 index 8b545467b..000000000 --- a/source/aggregation-tutorials.txt +++ /dev/null @@ -1,124 +0,0 @@ -.. _node-aggregation-tutorials-landing: - -===================== -Aggregation Tutorials -===================== - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: node.js, code example, runnable app - :description: Explore step-by-step aggregation tutorials for common tasks using the MongoDB Node.js Driver, including setup instructions and runnable code examples. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 1 - :class: singlecol - -.. toctree:: - - Filtered Subset - Group & Total - Unpack Arrays & Group - One-to-One Join - Multi-Field Join - -Overview --------- - -Aggregation tutorials provide detailed explanations of common -aggregation tasks in a step-by-step format. The tutorials are adapted -from examples in the `Practical MongoDB Aggregations book -`__ by Paul Done. - -Each tutorial includes the following sections: - -- **Introduction**, which describes the purpose and common use cases of the - aggregation type. This section also describes the example and desired - outcome that the tutorial demonstrates. - -- **Before You Get Started**, which describes the necessary databases, - collections, and sample data that you must have before building the - aggregation pipeline and performing the aggregation. - -- **Tutorial**, which describes how to build and run the aggregation - pipeline. This section describes each stage of the completed - aggregation tutorial, and then explains how to run and interpret the - output of the aggregation. - -At the end of each aggregation tutorial, you can find a link to a fully -runnable Node.js code file that you can run in your environment. - -.. tip:: - - To learn more about performing aggregations, see the - :ref:`node-aggregation` guide. - -.. _node-agg-tutorial-template-app: - -Aggregation Template App ------------------------- - -Before you begin following an aggregation tutorial, you must set up a -new Node.js app. You can use this app to connect to a MongoDB -deployment, insert sample data into MongoDB, and run the aggregation -pipeline in each tutorial. - -.. tip:: - - To learn how to install the driver and connect to MongoDB, - see the :ref:`node-quick-start-download-and-install` and - :ref:`node-quick-start-create-deployment` steps of the - Quick Start guide. - -Once you install the driver, create a file called -``agg_tutorial.js``. Paste the following code in this file to create an -app template for the aggregation tutorials: - -.. literalinclude:: /includes/aggregation/template-app.js - :language: javascript - :copyable: true - -.. important:: - - In the preceding code, read the code comments to find the sections of - the code that you must modify for the tutorial you are following. - - If you attempt to run the code without making any changes, you will - encounter a connection error. - -For every tutorial, you must replace the connection string placeholder with -your deployment's connection string. - -.. tip:: - - To learn how to locate your deployment's connection string, see the - :ref:`node-quick-start-connection-string` step of the Quick Start guide. - -For example, if your connection string is -``"mongodb+srv://mongodb-example:27017"``, your connection string assignment resembles -the following: - -.. code-block:: javascript - :copyable: false - - const uri = "mongodb+srv://mongodb-example:27017"; - -To run the completed file after you modify the template for a -tutorial, run the following command in your shell: - -.. code-block:: bash - - node agg_tutorial.js - -Available Tutorials -------------------- - -- :ref:`node-aggregation-filtered-subset` -- :ref:`node-aggregation-group-total` -- :ref:`node-aggregation-arrays` -- :ref:`node-aggregation-one-to-one` -- :ref:`node-aggregation-multi-field` \ No newline at end of file diff --git a/source/fundamentals/aggregation.txt b/source/aggregation.txt similarity index 56% rename from source/fundamentals/aggregation.txt rename to source/aggregation.txt index a158b589a..7043a839c 100644 --- a/source/fundamentals/aggregation.txt +++ b/source/aggregation.txt @@ -5,7 +5,12 @@ Aggregation =========== +.. facet:: + :name: genre + :values: reference + .. meta:: + :keywords: node.js, code example, runnable app :description: Learn to use aggregation operations in the MongoDB Node.js Driver to create pipelines for data transformation and summarization. .. contents:: On this page @@ -14,6 +19,14 @@ Aggregation :depth: 2 :class: singlecol +.. toctree:: + + Filtered Subset + Group & Total + Unpack Arrays & Group + One-to-One Join + Multi-Field Join + .. _nodejs-aggregation-overview: Overview @@ -101,7 +114,7 @@ database: .. tip:: - For more information on connecting to your MongoDB deployment, see the :doc:`Connection Guide `. + For more information on connecting to your MongoDB deployment, see the :doc:`Connection Guide `. Aggregation Example ~~~~~~~~~~~~~~~~~~~ @@ -134,6 +147,106 @@ This example produces the following output: For more information, see the `aggregate() API documentation <{+api+}/classes/Collection.html#aggregate>`__. +.. _node-aggregation-tutorials-landing: +.. _node-aggregation-tutorials: + +Aggregation Tutorials +--------------------- + +Aggregation tutorials provide detailed explanations of common +aggregation tasks in a step-by-step format. The tutorials are adapted +from examples in the `Practical MongoDB Aggregations book +`__ by Paul Done. + +Each tutorial includes the following sections: + +- **Introduction**, which describes the purpose and common use cases of the + aggregation type. This section also describes the example and desired + outcome that the tutorial demonstrates. + +- **Before You Get Started**, which describes the necessary databases, + collections, and sample data that you must have before building the + aggregation pipeline and performing the aggregation. + +- **Tutorial**, which describes how to build and run the aggregation + pipeline. This section describes each stage of the completed + aggregation tutorial, and then explains how to run and interpret the + output of the aggregation. + +At the end of each aggregation tutorial, you can find a link to a fully +runnable Node.js code file that you can run in your environment. + +.. tip:: + + To learn more about performing aggregations, see the + :ref:`node-aggregation` guide. + +.. _node-agg-tutorial-template-app: + +Aggregation Template App +~~~~~~~~~~~~~~~~~~~~~~~~ + +Before you begin following an aggregation tutorial, you must set up a +new Node.js app. You can use this app to connect to a MongoDB +deployment, insert sample data into MongoDB, and run the aggregation +pipeline in each tutorial. + +.. tip:: + + To learn how to install the driver and connect to MongoDB, + see the :ref:`node-get-started-download-and-install` and + :ref:`node-get-started-create-deployment` steps of the + Quick Start guide. + +Once you install the driver, create a file called +``agg_tutorial.js``. Paste the following code in this file to create an +app template for the aggregation tutorials: + +.. literalinclude:: /includes/aggregation/template-app.js + :language: javascript + :copyable: true + +.. important:: + + In the preceding code, read the code comments to find the sections of + the code that you must modify for the tutorial you are following. + + If you attempt to run the code without making any changes, you will + encounter a connection error. + +For every tutorial, you must replace the connection string placeholder with +your deployment's connection string. + +.. tip:: + + To learn how to locate your deployment's connection string, see the + :ref:`node-get-started-connection-string` step of the Quick Start guide. + +For example, if your connection string is +``"mongodb+srv://mongodb-example:27017"``, your connection string assignment resembles +the following: + +.. code-block:: javascript + :copyable: false + + const uri = "mongodb+srv://mongodb-example:27017"; + +To run the completed file after you modify the template for a +tutorial, run the following command in your shell: + +.. code-block:: bash + + node agg_tutorial.js + +Available Tutorials +~~~~~~~~~~~~~~~~~~~ + +- :ref:`node-aggregation-filtered-subset` +- :ref:`node-aggregation-group-total` +- :ref:`node-aggregation-arrays` +- :ref:`node-aggregation-one-to-one` +- :ref:`node-aggregation-multi-field` + Additional Examples ~~~~~~~~~~~~~~~~~~~ diff --git a/source/aggregation-tutorials/filtered-subset.txt b/source/aggregation/filtered-subset.txt similarity index 100% rename from source/aggregation-tutorials/filtered-subset.txt rename to source/aggregation/filtered-subset.txt diff --git a/source/aggregation-tutorials/group-total.txt b/source/aggregation/group-total.txt similarity index 100% rename from source/aggregation-tutorials/group-total.txt rename to source/aggregation/group-total.txt diff --git a/source/aggregation-tutorials/multi-field-join.txt b/source/aggregation/multi-field-join.txt similarity index 100% rename from source/aggregation-tutorials/multi-field-join.txt rename to source/aggregation/multi-field-join.txt diff --git a/source/aggregation-tutorials/one-to-one-join.txt b/source/aggregation/one-to-one-join.txt similarity index 100% rename from source/aggregation-tutorials/one-to-one-join.txt rename to source/aggregation/one-to-one-join.txt diff --git a/source/aggregation-tutorials/unpack-arrays.txt b/source/aggregation/unpack-arrays.txt similarity index 100% rename from source/aggregation-tutorials/unpack-arrays.txt rename to source/aggregation/unpack-arrays.txt diff --git a/source/fundamentals/collations.txt b/source/archive-reference-files/collations.txt similarity index 99% rename from source/fundamentals/collations.txt rename to source/archive-reference-files/collations.txt index a4474eb21..2ad831cbd 100644 --- a/source/fundamentals/collations.txt +++ b/source/archive-reference-files/collations.txt @@ -1,4 +1,5 @@ .. _node-fundamentals-collations: +.. _node-collations: ========== Collations @@ -58,7 +59,7 @@ Usage ----- You can specify a collation when you create a new collection or new index. You -can also specify a collation for :doc:`CRUD operations ` +can also specify a collation for :doc:`CRUD operations ` and aggregations. When you create a new collection with a collation, you define the default diff --git a/source/quick-start/connect-to-mongodb.txt b/source/archive-reference-files/quick-start/connect-to-mongodb.txt similarity index 100% rename from source/quick-start/connect-to-mongodb.txt rename to source/archive-reference-files/quick-start/connect-to-mongodb.txt diff --git a/source/quick-start/create-a-connection-string.txt b/source/archive-reference-files/quick-start/create-a-connection-string.txt similarity index 100% rename from source/quick-start/create-a-connection-string.txt rename to source/archive-reference-files/quick-start/create-a-connection-string.txt diff --git a/source/quick-start/create-a-deployment.txt b/source/archive-reference-files/quick-start/create-a-deployment.txt similarity index 100% rename from source/quick-start/create-a-deployment.txt rename to source/archive-reference-files/quick-start/create-a-deployment.txt diff --git a/source/quick-start/download-and-install.txt b/source/archive-reference-files/quick-start/download-and-install.txt similarity index 100% rename from source/quick-start/download-and-install.txt rename to source/archive-reference-files/quick-start/download-and-install.txt diff --git a/source/quick-start/facets.toml b/source/archive-reference-files/quick-start/facets.toml similarity index 100% rename from source/quick-start/facets.toml rename to source/archive-reference-files/quick-start/facets.toml diff --git a/source/quick-start/next-steps.txt b/source/archive-reference-files/quick-start/next-steps.txt similarity index 100% rename from source/quick-start/next-steps.txt rename to source/archive-reference-files/quick-start/next-steps.txt diff --git a/source/fundamentals/connection.txt b/source/connect.txt similarity index 65% rename from source/fundamentals/connection.txt rename to source/connect.txt index c768dba01..55526a6ec 100644 --- a/source/fundamentals/connection.txt +++ b/source/connect.txt @@ -1,34 +1,34 @@ -.. _node-connection: +.. _node-connect: -========== -Connection -========== +================== +Connect to MongoDB +================== -.. default-domain:: mongodb +.. 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 connect to MongoDB. + :keywords: client, ssl -.. meta:: - :description: Learn how to configure your application's connection to a MongoDB deployment by using the Node.js driver. - :keywords: node.js +.. toctree:: + :titlesonly: + :maxdepth: 1 .. toctree:: - Connection Guide - Connection Options - Network Compression - TLS - SOCKS5 Proxy Support - Limit Server Execution Time + Create a MongoClient + Connection Options + Choose a Connection Target Connect with AWS Lambda - -.. contents:: On this page - :local: - :backlinks: none - :depth: 1 - :class: singlecol + Connection Troubleshooting Overview -------- @@ -37,7 +37,7 @@ Learn how to configure your application's connection to a MongoDB deployment using the Node.js driver. In the following sections, you will learn: -- :ref:`How to Connect to MongoDB ` +- :ref:`How to Create a MongoClient ` - :ref:`The Available Connection Options ` - :ref:`How to Enable Network Compression ` - :ref:`How to Enable TLS on a Connection ` diff --git a/source/fundamentals/connection/connection-options.txt b/source/connect/connection-options.txt similarity index 96% rename from source/fundamentals/connection/connection-options.txt rename to source/connect/connection-options.txt index e0f4cb4ff..a5afce3c0 100644 --- a/source/fundamentals/connection/connection-options.txt +++ b/source/connect/connection-options.txt @@ -1,8 +1,8 @@ .. _node-connection-options: -================== -Connection Options -================== +========================== +Specify Connection Options +========================== .. facet:: :name: genre @@ -12,6 +12,16 @@ Connection Options :keywords: node.js, customize :description: Explore connection and authentication options available in the MongoDB Node.js Driver, including settings for app name, authentication mechanisms, and TLS configurations. +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Compress Network Traffic + Customize Server Selection + Stable API + Limit Server Execution Time + Connection Pools + This section explains the MongoDB connection and authentication options supported by the {+driver-short+} that you can set within a ``MongoClientOptions`` instance. diff --git a/source/connect/connection-options/connection-pools.txt b/source/connect/connection-options/connection-pools.txt new file mode 100644 index 000000000..2050239bf --- /dev/null +++ b/source/connect/connection-options/connection-pools.txt @@ -0,0 +1,30 @@ +.. _node-connection-pools: + +================ +Connection Pools +================ + +.. facet:: + :name: genre + :values: reference + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +In this guide, you can learn about how {+driver-short+} uses connection pools to manage +connections to a MongoDB deployment and how you can configure connection pool settings +in your application. + +A connection pool is a cache of open database connections maintained by {+driver-short+}. +When your application requests a connection to MongoDB, {+driver-short+} seamlessly +gets 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 new connections +are created by {+driver-short+}. \ No newline at end of file diff --git a/source/fundamentals/connection/csot.txt b/source/connect/connection-options/csot.txt similarity index 100% rename from source/fundamentals/connection/csot.txt rename to source/connect/connection-options/csot.txt diff --git a/source/fundamentals/connection/network-compression.txt b/source/connect/connection-options/network-compression.txt similarity index 100% rename from source/fundamentals/connection/network-compression.txt rename to source/connect/connection-options/network-compression.txt diff --git a/source/connect/connection-options/server-selection.txt b/source/connect/connection-options/server-selection.txt new file mode 100644 index 000000000..d7798049b --- /dev/null +++ b/source/connect/connection-options/server-selection.txt @@ -0,0 +1,21 @@ +.. _node-server-selection: + +========================== +Customize Server Selection +========================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example, read preference, write + +Overview +-------- \ No newline at end of file diff --git a/source/fundamentals/stable-api.txt b/source/connect/connection-options/stable-api.txt similarity index 100% rename from source/fundamentals/stable-api.txt rename to source/connect/connection-options/stable-api.txt diff --git a/source/connect/connection-targets.txt b/source/connect/connection-targets.txt new file mode 100644 index 000000000..df72aba8a --- /dev/null +++ b/source/connect/connection-targets.txt @@ -0,0 +1,18 @@ +.. _node-connection-targets: + +========================== +Choose a Connection Target +========================== + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: connection string, URI, server, settings, client, load balancing, srv, dns + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol \ No newline at end of file diff --git a/source/connection-troubleshooting.txt b/source/connect/connection-troubleshooting.txt similarity index 100% rename from source/connection-troubleshooting.txt rename to source/connect/connection-troubleshooting.txt diff --git a/source/fundamentals/connection/connect.txt b/source/connect/mongoclient.txt similarity index 95% rename from source/fundamentals/connection/connect.txt rename to source/connect/mongoclient.txt index 17fb36766..a0176ab71 100644 --- a/source/fundamentals/connection/connect.txt +++ b/source/connect/mongoclient.txt @@ -1,16 +1,16 @@ -.. _node-connect-to-mongodb: +.. _node-mongoclient: -================ -Connection Guide -================ +==================== +Create a MongoClient +==================== .. facet:: :name: genre :values: reference .. meta:: - :description: Learn how to connect to a MongoDB Atlas or local MongoDB deployment by using the Node.js driver. - :keywords: node.js, code example, connection string, local connection, Stable API, Atlas + :description: Learn how to create a MongoClient using the {+driver-short+}. + :keywords: connection string, URI, server, Atlas, settings, client .. contents:: On this page :local: diff --git a/source/crud.txt b/source/crud.txt new file mode 100644 index 000000000..abf96d299 --- /dev/null +++ b/source/crud.txt @@ -0,0 +1,38 @@ +.. _node-crud-landing: +.. _node-crud-operations: + +=============== +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 + Delete Documents + Bulk Write Operations + Compound Operations + Transactions + Configure CRUD Operations + Operations on Replica Sets + Store Large Files + +CRUD (Create, Read, Update, Delete) operations enable you to work with +data stored in MongoDB. \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations/bulk.txt b/source/crud/bulk-write.txt similarity index 99% rename from source/fundamentals/crud/write-operations/bulk.txt rename to source/crud/bulk-write.txt index 7cba6ee8a..35c9c6310 100644 --- a/source/fundamentals/crud/write-operations/bulk.txt +++ b/source/crud/bulk-write.txt @@ -1,4 +1,4 @@ -.. _node-fundamentals-bulk: +.. _node-bulk-write: =============== Bulk Operations diff --git a/source/fundamentals/crud/compound-operations.txt b/source/crud/compound-operations.txt similarity index 100% rename from source/fundamentals/crud/compound-operations.txt rename to source/crud/compound-operations.txt diff --git a/source/crud/configure.txt b/source/crud/configure.txt new file mode 100644 index 000000000..521f75e68 --- /dev/null +++ b/source/crud/configure.txt @@ -0,0 +1,321 @@ +.. _node-configure: + +========================= +Configure CRUD Operations +========================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: insert, update, replace, delete, options, code example + +Overview +-------- + +In this guide, you can learn how to configure read and write operations in {+driver-short+}. + +.. _node-fundamentals-collations: +.. _node-collations: + +Collations +---------- + +*Collations are available in MongoDB 3.4 and later.* + +You can use **collations**, a set of sorting rules, to run operations using +string ordering for specific languages and locales (a community or region that +shares common language idioms). + +MongoDB sorts strings using *binary collation* by default. This collation +method uses the `ASCII standard `_ +character values to compare and order strings. Languages and locales +have specific character ordering conventions that differ from the ASCII +standard. + +For example, in Canadian French, the right-most accented character determines +the ordering for strings when the other characters are the same. Consider the +following French words: **cote**, **coté**, **côte**, and **côté**. + +MongoDB sorts them in the following order using the default binary collation: + +.. code-block:: none + + cote + coté + côte + côté + +MongoDB sorts them in the following order using the Canadian French collation: + +.. code-block:: none + + cote + côte + coté + côté + +Using Collations +~~~~~~~~~~~~~~~~~~ + +You can specify a collation when you create a new collection or new index. You +can also specify a collation for :doc:`CRUD operations ` +and aggregations. + +When you create a new collection with a collation, you define the default +collation for any of the :manual:`operations that support collation +` called on that +collection. You can override the collation for an operation by specifying a +different one. + +.. note:: + + Currently, you cannot create a collation on an existing collection. To use + collations with an existing collection, create an index with the collation + and specify the same collation in your operations on it. + +When you create an index with a collation, you specify the sort order for +operations that use that index. To use the collation in the index, you +must provide a matching collation in the operation, and the operation must +use the index. While most index types support collation, the following +types support only binary comparison: + +- :manual:`text ` +- :manual:`2d ` +- :manual:`geoHaystack ` + +Collation Parameters +~~~~~~~~~~~~~~~~~~~~ + +The collation object contains the following parameters: + +.. code-block:: javascript + + collation: { + locale: , + caseLevel: , + caseFirst: , + strength: , + numericOrdering: , + alternate: , + maxVariable: , + backwards: + } + +You must specify the ``locale`` field in the collation; all other fields +are optional. For a complete list of supported locales and the default values +for the ``locale`` fields, see :manual:`Supported Languages and Locales +`. +For descriptions of each field, see the :manual:`Collation Document MongoDB +manual entry `. + +Set a Default Collation on a Collection +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In the following example, we create a new collection called ``souvenirs`` and +assign a default collation with the ``"fr_CA"`` locale. The collation applies +to all :manual:`operations that support collation +` performed on that +collection. + +.. literalinclude:: /code-snippets/collation/collection-collation.js + :language: javascript + :start-after: start collection collation + :end-before: end collection collation + +Any of the operations that support collations automatically apply the collation +defined on the collection. The query below searches the ``souvenirs`` +collection and applies the ``"fr_CA"`` locale collation: + +.. literalinclude:: /code-snippets/collation/collection-auto-collation.js + :language: javascript + :start-after: start auto collation + :end-before: end auto collation + +You can specify a different collation as a parameter in an operation that +supports collations. The following query specifies the ``"is"`` Iceland locale +and ``caseFirst`` optional parameter with the value ``"upper"``: + +.. literalinclude:: /code-snippets/collation/collection-specify-collation.js + :language: javascript + :start-after: start specified collation + :end-before: end specified collation + +Assign a Collation to an Index +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In the following example, we create a new index on the ``title`` field of +a collection with a collation set to the ``"en_US"`` locale. + +.. literalinclude:: /code-snippets/collation/index-collation.js + :language: javascript + :start-after: start create index collation + :end-before: end create index collation + +The following query uses the index we created: + +.. literalinclude:: /code-snippets/collation/query-index-collation.js + :language: javascript + :start-after: start query index collation + :end-before: end query index collation + +The following queries **do not** use the index that we created. The first +query does not include a collation and the second contains a different +strength value than the collation on the index. + +.. literalinclude:: /code-snippets/collation/query-not-indexed-collation.js + :language: javascript + :start-after: start not indexed collation + :end-before: end not indexed collation + +.. literalinclude:: /code-snippets/collation/query-index-no-collation.js + :language: javascript + :start-after: start index no collation + :end-before: end index no collation + +Collation Query Examples +~~~~~~~~~~~~~~~~~~~~~~~~ + +Operations that read, update, and delete documents from a collection can use +collations. This section includes examples of a selection of these. See the +MongoDB manual for a full list of :manual:`operations that support collation +`. + +find() and sort() Example +````````````````````````` + +The following example calls both ``find()`` and ``sort()`` on a collection +that uses the default binary collation. We use the German collation by +setting the value of the ``locale`` parameter to ``"de"``. + +.. literalinclude:: /code-snippets/collation/find-sort-collation.js + :language: javascript + :start-after: start find sort collation + :end-before: end find sort collation + +findOneAndUpdate() Example +`````````````````````````` + +The following example calls the ``findOneAndUpdate()`` operation on a +collection that uses the default binary collation. The collection contains the +following documents: + +.. code-block:: none + + { "_id" : 1, "first_name" : "Hans" } + { "_id" : 2, "first_name" : "Gunter" } + { "_id" : 3, "first_name" : "Günter" } + { "_id" : 4, "first_name" : "Jürgen" } + +Consider the following ``findOneAndUpdate()`` operation on this collection +which **does not** specify a collation: + +.. literalinclude:: /code-snippets/collation/findOneAndUpdate-default-order-collation.js + :language: javascript + :start-after: start findOneAndUpdate default order collation + :end-before: end findOneAndUpdate default order collation + +Since "Gunter" is the first sorted result when using a binary collation, none +of the documents come lexically before and match the ``$lt`` comparison +operator in the query document. As a result, the operation does not update any +documents. + +Consider the same operation with a collation specified with the locale set to +``de@collation=phonebook``. This locale specifies the ``collation=phonebook`` +option which contains rules for prioritizing proper nouns, identified by +capitalization of the first letter. The ``de@collation=phonebook`` locale and +option sorts characters with umlauts before the same characters without +umlauts. + +.. literalinclude:: /code-snippets/collation/findOneAndUpdate-collation.js + :language: javascript + :start-after: start findOneAndUpdate collation + :end-before: end findOneAndUpdate collation + +Since "Günter" lexically comes before "Gunter" using the +``de@collation=phonebook`` collation specified in ``findOneAndUpdate()``, +the operation returns the following updated document: + +.. code-block:: none + + { lastErrorObject: { updatedExisting: true, n: 1 }, + value: { _id: 3, first_name: 'Günter' }, + ok: 1 } + +findOneAndDelete() Example +`````````````````````````` + +The following example calls the ``findOneAndDelete()`` operation on a +collection that uses the default binary collation and contains the following +documents: + +.. code-block:: none + + { "_id" : 1, "a" : "16" } + { "_id" : 2, "a" : "84" } + { "_id" : 3, "a" : "179" } + +In this example, we set the ``numericOrdering`` collation parameter to ``true`` +to sort numeric strings based on their numerical order instead of their +lexical order. + +.. literalinclude:: /code-snippets/collation/findOneAndDelete-collation.js + :language: javascript + :start-after: start findOneAndDelete collation + :end-before: end findOneAndDelete collation + +After you run the operation above, the collection contains the following +documents: + +.. code-block:: none + + { "_id" : 1, "a" : "16" } + { "_id" : 2, "a" : "84" } + +If you perform the same operation without collation on the original +collection of three documents, it matches documents based on the lexical value +of the strings (``"16"``, ``"84"``, and ``"179"``), and deletes the first +document it finds that matches the query criteria. + +.. literalinclude:: /code-snippets/collation/findOneAndDelete-no-collation.js + :language: javascript + :start-after: start findOneAndDelete no collation + :end-before: end findOneAndDelete no collation + +Since all the documents contain lexical values in the ``a`` field that +match the criteria (greater than the lexical value of ``"100"``), the operation +removes the first result. After you run the operation above, the collection +contains the following documents: + +.. code-block:: none + + { "_id" : 2, "a" : "84" } + { "_id" : 3, "a" : "179" } + +Aggregation Example +``````````````````` + +To use collation with the `aggregate <{+api+}/classes/Collection.html#aggregate>`__ +operation, pass the collation document in the options field, after the +array of pipeline stages. + +The following example shows an aggregation pipeline on a collection that uses +the default binary collation. The aggregation groups the ``first_name`` field, +counts the total number of results in each group, and sorts the results by +the German phonebook (``"de@collation=phonebook"`` locale) order. + +.. note:: + + You can specify only one collation on an aggregation. + +.. literalinclude:: /code-snippets/collation/aggregation-collation.js + :language: javascript + :start-after: start aggregation collation + :end-before: end aggregation collation diff --git a/source/fundamentals/crud/write-operations/delete.txt b/source/crud/delete.txt similarity index 99% rename from source/fundamentals/crud/write-operations/delete.txt rename to source/crud/delete.txt index cfb8c374a..fe388e822 100644 --- a/source/fundamentals/crud/write-operations/delete.txt +++ b/source/crud/delete.txt @@ -1,4 +1,5 @@ .. _node-fundamentals-delete: +.. _node-delete: ================ Delete Documents diff --git a/source/fundamentals/gridfs.txt b/source/crud/gridfs.txt similarity index 99% rename from source/fundamentals/gridfs.txt rename to source/crud/gridfs.txt index 514f300b6..cd7cfc4b5 100644 --- a/source/fundamentals/gridfs.txt +++ b/source/crud/gridfs.txt @@ -168,7 +168,7 @@ see the following resources: - `find() API documentation <{+api+}/classes/GridFSBucket.html#find>`__ - `FindCursor API documentation <{+api+}/classes/FindCursor.html>`__ - :doc:`Cursor Fundamentals page ` -- :doc:`Read Operations page ` +- :doc:`Query Operations page ` .. _gridfs-download-files: diff --git a/source/fundamentals/crud/write-operations/insert.txt b/source/crud/insert.txt similarity index 99% rename from source/fundamentals/crud/write-operations/insert.txt rename to source/crud/insert.txt index d6da4aa81..daf2bda5d 100644 --- a/source/fundamentals/crud/write-operations/insert.txt +++ b/source/crud/insert.txt @@ -1,4 +1,5 @@ .. _node-fundamentals-insert-data: +.. _node-insert: ================ Insert Documents diff --git a/source/fundamentals/crud/write-operations/pkFactory.txt b/source/crud/pkFactory.txt similarity index 100% rename from source/fundamentals/crud/write-operations/pkFactory.txt rename to source/crud/pkFactory.txt diff --git a/source/crud/query.txt b/source/crud/query.txt new file mode 100644 index 000000000..b8e793575 --- /dev/null +++ b/source/crud/query.txt @@ -0,0 +1,253 @@ +.. _node-read-operations: +.. _node-query: + +================ +Query Operations +================ + +.. 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 + +.. meta:: + :keywords: code example, node.js, sample dataset + +.. toctree:: + :maxdepth: 1 + + Find Documents + Specify Documents to Return + Specify Fields to Return + Specify a Query + Count Documents + Distinct Field Values + Search Text + Access Data from a Cursor + Geospatial Queries + +.. _nodejs-driver-retrieve-data-overview: + +Overview +-------- + +You can perform find operations to retrieve data from your MongoDB database. +You can perform a find operation to match documents on a set of criteria +by calling the ``find()`` or ``findOne()`` method. + +.. tip:: Interactive Lab + + This page includes a short interactive lab that demonstrates how to + retrieve data by using the ``find()`` method. You can complete this lab + directly in your browser window without installing MongoDB or a code editor. + + To start the lab, click the :guilabel:`Open Interactive Tutorial` button at the + top of the page. To expand the lab to a full-screen format, click the + full-screen button (:guilabel:`⛶`) in the top-right corner of the lab pane. + +You can also further specify the information that the find operation +returns by specifying optional parameters or by chaining other methods, +as shown in the following guides: + +- :ref:`node-fundamentals-sort` +- :ref:`node-fundamentals-skip` +- :ref:`node-fundamentals-limit` +- :ref:`node-fundamentals-project` + +You can also use an aggregation operation to retrieve data. This type of +operation allows you to apply an ordered pipeline of transformations to the +matched data. + +If you want to monitor the database for incoming data that matches a set of +criteria, you can use the watch operation to be notified in real-time when +matching data is inserted. + +.. include:: /includes/access-cursor-note.rst + +.. |page-topic| replace:: perform read operations +.. |link-topic-ing| replace:: performing read operations in the Atlas UI + +.. |atlas-url| replace:: :atlas:`View, Filter, and Sort Documents ` + +.. include:: /includes/fact-atlas-compatible.rst +.. include:: /includes/fact-atlas-link.rst + +Find Documents +-------------- + +You can call the ``find()`` method on a ``Collection`` object. The +method accepts a query document that describes the documents you want to +retrieve. For more information on how to specify your query document, +see the :ref:`node-fundamentals-query-document` guide. + +.. tip:: No Query Criteria + + To execute a find operation that has no query criteria, you can + pass an empty query or omit the query document in your find + method parameters. + + The following operations both return all documents in the + ``myColl`` collection: + + .. code-block:: javascript + + myColl.find(); // no query + myColl.find({}); // empty query + + If you don't pass a query or pass an empty query + to the ``findOne()`` method, the operation returns a single + document from a collection. + + You can specify options in a find operation even when you pass an + empty query. For example, the following code shows how you can + specify a projection as an option while executing a find operation + that receives an empty query parameter: + + .. code-block:: javascript + + const options = { + projection: { _id: 0, field1: 1 }, + }; + + const findResult = await myColl.findOne({}, options); + + For more information about projecting document fields, see the + :ref:`node-fundamentals-project` guide. + +The ``find()`` method returns a ``Cursor`` instance from which you can +access the matched documents. The ``findOne()`` method returns a ``Promise`` +instance, which you can resolve to access either the matching document or +a ``null`` value if there are no matches. + +.. example:: + + A pizza restaurant wants to find all pizzas ordered by Lemony Snicket + yesterday. They run the following ``find()`` query on the + ``orders`` collection: + + .. literalinclude:: /code-snippets/crud/pizza.js + :language: javascript + :start-after: start find crud example + :end-before: end find crud example + + Once the operation returns, the ``findResult`` variable references a + ``Cursor``. You can print the documents retrieved using the ``for await...of`` + syntax as shown below: + + .. code-block:: javascript + + for await (const doc of findResult) { + console.log(doc); + } + + The output might resemble the following: + + .. code-block:: javascript + :copyable: false + + [ + { name: "Lemony Snicket", type: "horseradish pizza", qty: 1, status: "delivered", date: ... }, + { name: "Lemony Snicket", type: "coal-fired oven pizza", qty: 3, status: "canceled", date: ...}, + ... + ] + +Additional Information +~~~~~~~~~~~~~~~~~~~~~~ + +For runnable code examples that demonstrate find operations, see the following +usage examples: + +- :ref:`node-usage-findone` +- :ref:`node-usage-find` + +For more information about the ``findOne()`` and ``find()`` methods, see the +following Server manual documentation: + +- :manual:`findOne() ` +- :manual:`find() ` + +Aggregate Data from Documents +----------------------------- + +If you want to run a custom processing pipeline to retrieve data from your +database, you can use the ``aggregate()`` method. This method accepts +aggregation expressions to run in sequence. These expressions let you filter, +group, and arrange the result data from a collection. + +.. example:: + + A pizza restaurant wants to run a status report on-demand to + summarize pizza orders over the past week. They run the following + ``aggregate()`` query on the ``orders`` collection to fetch the + totals for each distinct "status" field: + + .. literalinclude:: /code-snippets/crud/pizza.js + :language: javascript + :start-after: start aggregate crud example + :end-before: end aggregate crud example + + Once the operation returns, the ``aggregateResult`` variable references a + ``Cursor``. You can print the documents retrieved using the ``for await...of`` + syntax as shown below: + + .. code-block:: javascript + + for await (const doc of aggregateResult) { + console.log(doc); + } + + The output might resemble the following: + + .. code-block:: javascript + :copyable: false + + [ + { _id: 'delivering', count: 5 }, + { _id: 'delivered', count: 37 }, + { _id: 'created', count: 9 } + ] + +Additional Information +~~~~~~~~~~~~~~~~~~~~~~ + +For more information on how to construct an aggregation pipeline, see +the :ref:`node-aggregation` guide or :manual:`Aggregation Operations ` +in the Server manual. + +.. _node-fundamentals-watch: + +Monitor Data Changes +-------------------- + +You can use the ``watch()`` method to monitor a collection for changes to +a collection that match certain criteria. These changes include inserted, +updated, replaced, and deleted documents. You can pass this method +a pipeline of aggregation commands that sequentially runs on the changed +data whenever write operations are executed on the collection. + +.. example:: + + A pizza restaurant wants to receive a notification whenever a new pizza + order comes in. To accomplish this, they create an aggregation pipeline + to filter on insert operations and return specific fields. They pass + this pipeline to the ``watch()`` method called on the ``orders`` + collection as shown below: + + .. literalinclude:: /code-snippets/crud/pizza.js + :language: javascript + :start-after: start watch crud example + :end-before: end watch crud example + +Additional Information +~~~~~~~~~~~~~~~~~~~~~~ + +For a runnable example of the ``watch()`` method, see the +:ref:`Watch for Changes ` usage example. + +.. _node-retrieve-instruqt-lab: + +.. instruqt:: /mongodb-docs/tracks/find-node?token=em_OVNHWCPNPMLwNOCm + :title: find() Lesson + :drawer: \ No newline at end of file diff --git a/source/usage-examples/count.txt b/source/crud/query/count.txt similarity index 99% rename from source/usage-examples/count.txt rename to source/crud/query/count.txt index d995917fd..e272af18d 100644 --- a/source/usage-examples/count.txt +++ b/source/crud/query/count.txt @@ -1,4 +1,5 @@ .. _node-usage-count: +.. _node-count: =============== Count Documents diff --git a/source/fundamentals/crud/read-operations/cursor.txt b/source/crud/query/cursor.txt similarity index 99% rename from source/fundamentals/crud/read-operations/cursor.txt rename to source/crud/query/cursor.txt index d3360c592..bbe4212fa 100644 --- a/source/fundamentals/crud/read-operations/cursor.txt +++ b/source/crud/query/cursor.txt @@ -1,4 +1,5 @@ .. _node-access-cursor: +.. _node-cursor: ========================= Access Data From a Cursor diff --git a/source/fundamentals/crud/read-operations/distinct.txt b/source/crud/query/distinct.txt similarity index 99% rename from source/fundamentals/crud/read-operations/distinct.txt rename to source/crud/query/distinct.txt index 6280fdb4d..96aa5ca06 100644 --- a/source/fundamentals/crud/read-operations/distinct.txt +++ b/source/crud/query/distinct.txt @@ -1,4 +1,5 @@ .. _node-fundamentals-distinct: +.. _node-distinct: ======================== Retrieve Distinct Values diff --git a/source/fundamentals/crud/read-operations/geo.txt b/source/crud/query/geo.txt similarity index 98% rename from source/fundamentals/crud/read-operations/geo.txt rename to source/crud/query/geo.txt index 8c5a29a6c..856df7290 100644 --- a/source/fundamentals/crud/read-operations/geo.txt +++ b/source/crud/query/geo.txt @@ -1,4 +1,5 @@ .. _node-fundamentals-geospatial: +.. _node-geospatial: =================== Search Geospatially @@ -110,7 +111,7 @@ Examples -------- The following examples use the MongoDB Atlas sample dataset. You can learn how to set up your own free-tier Atlas cluster and how to load the sample dataset in our -:doc:`quick start guide `. +:doc:`get started guide `. The examples use the ``theaters`` collection in the ``sample_mflix`` database from the sample dataset. The ``theaters`` collection contains a ``2dsphere`` index diff --git a/source/fundamentals/crud/read-operations/project.txt b/source/crud/query/project.txt similarity index 99% rename from source/fundamentals/crud/read-operations/project.txt rename to source/crud/query/project.txt index 1f23bbc39..1581a8cf1 100644 --- a/source/fundamentals/crud/read-operations/project.txt +++ b/source/crud/query/project.txt @@ -1,4 +1,5 @@ .. _node-fundamentals-project: +.. _node-project: ============================== Specify Which Fields to Return diff --git a/source/fundamentals/crud/query-document.txt b/source/crud/query/query-document.txt similarity index 99% rename from source/fundamentals/crud/query-document.txt rename to source/crud/query/query-document.txt index c5ce1852e..d9835dcdc 100644 --- a/source/fundamentals/crud/query-document.txt +++ b/source/crud/query/query-document.txt @@ -1,4 +1,5 @@ .. _node-fundamentals-query-document: +.. _node-query-document: =============== Specify a Query diff --git a/source/fundamentals/crud/read-operations/retrieve.txt b/source/crud/query/retrieve.txt similarity index 98% rename from source/fundamentals/crud/read-operations/retrieve.txt rename to source/crud/query/retrieve.txt index 59cfcf8c6..585d920b6 100644 --- a/source/fundamentals/crud/read-operations/retrieve.txt +++ b/source/crud/query/retrieve.txt @@ -1,8 +1,9 @@ .. _node-fundamentals-retrieve-data: +.. _node-find: -============= -Retrieve Data -============= +============== +Find Documents +============== .. facet:: :name: genre @@ -64,8 +65,8 @@ matching data is inserted. .. include:: /includes/fact-atlas-compatible.rst .. include:: /includes/fact-atlas-link.rst -Find Documents --------------- +Finding Documents +----------------- You can call the ``find()`` method on a ``Collection`` object. The method accepts a query document that describes the documents you want to diff --git a/source/crud/query/specify-documents-to-return.txt b/source/crud/query/specify-documents-to-return.txt new file mode 100644 index 000000000..508f266ea --- /dev/null +++ b/source/crud/query/specify-documents-to-return.txt @@ -0,0 +1,28 @@ +.. _node-specify-documents-to-return: + +=========================== +Specify Documents to Return +=========================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: read, paginate, pagination, order, code example + +Overview +-------- + +In this guide, you can learn how to specify which documents to return from a read +operation by using the following methods: + +- ``limit``: Specifies the maximum number of documents to return from a query. +- ``sort``: Specifies the sort order for the returned documents. +- ``skip``: Specifies the number of documents to skip before returning query results. \ No newline at end of file diff --git a/source/fundamentals/crud/read-operations/text.txt b/source/crud/query/text.txt similarity index 99% rename from source/fundamentals/crud/read-operations/text.txt rename to source/crud/query/text.txt index 2eb869b33..ae3d65200 100644 --- a/source/fundamentals/crud/read-operations/text.txt +++ b/source/crud/query/text.txt @@ -1,4 +1,5 @@ .. _node-fundamentals-text: +.. _node-search-text: =========== Search Text diff --git a/source/fundamentals/crud/read-write-pref.txt b/source/crud/read-write-pref.txt similarity index 100% rename from source/fundamentals/crud/read-write-pref.txt rename to source/crud/read-write-pref.txt diff --git a/source/fundamentals/transactions.txt b/source/crud/transactions.txt similarity index 99% rename from source/fundamentals/transactions.txt rename to source/crud/transactions.txt index 41e3c9214..cc983373d 100644 --- a/source/fundamentals/transactions.txt +++ b/source/crud/transactions.txt @@ -1,4 +1,5 @@ .. _nodejs-transactions: +.. _node-transactions: ============ Transactions diff --git a/source/fundamentals/crud/write-operations/upsert.txt b/source/crud/update.txt similarity index 93% rename from source/fundamentals/crud/write-operations/upsert.txt rename to source/crud/update.txt index ad400ded8..fbf2dd272 100644 --- a/source/fundamentals/crud/write-operations/upsert.txt +++ b/source/crud/update.txt @@ -1,8 +1,9 @@ .. _node-fundamentals-upsert: +.. _node-update: -====================================== -Insert or Update in a Single Operation -====================================== +================ +Update Documents +================ .. facet:: :name: genre @@ -18,6 +19,14 @@ Insert or Update in a Single Operation :depth: 1 :class: singlecol +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Modify Documents + Replace + Update Arrays + Overview -------- diff --git a/source/fundamentals/crud/write-operations/embedded-arrays.txt b/source/crud/update/embedded-arrays.txt similarity index 99% rename from source/fundamentals/crud/write-operations/embedded-arrays.txt rename to source/crud/update/embedded-arrays.txt index 668944b9e..2917e3e6f 100644 --- a/source/fundamentals/crud/write-operations/embedded-arrays.txt +++ b/source/crud/update/embedded-arrays.txt @@ -1,4 +1,5 @@ .. _node-fundamentals-update-array: +.. _node-update-arrays: =========================== Update Arrays in a Document diff --git a/source/fundamentals/crud/write-operations/modify.txt b/source/crud/update/modify.txt similarity index 95% rename from source/fundamentals/crud/write-operations/modify.txt rename to source/crud/update/modify.txt index 06624209d..b4bef4ad8 100644 --- a/source/fundamentals/crud/write-operations/modify.txt +++ b/source/crud/update/modify.txt @@ -1,4 +1,5 @@ .. _node-fundamentals-change-a-document: +.. _node-modify: ================ Modify Documents @@ -133,11 +134,10 @@ the ``quantity`` field and all other values unchanged: quantity: 5, } -If an update operation fails to match any documents in a collection, it -does not make any changes. Update operations can be configured to perform -an :doc:`upsert ` which -attempts to perform an update, but if no documents are matched, inserts -a new document with the specified fields and values. +If an update operation fails to match any documents in a collection, it does not +make any changes. Update operations can be configured to perform an :doc:`upsert +` which attempts to perform an update, but if no documents are +matched, inserts a new document with the specified fields and values. You cannot modify the ``_id`` field of a document nor change a field to a value that violates a unique index constraint. See the {+mdb-server+} manual @@ -216,7 +216,7 @@ and the immutable ``_id`` field as follows: If a replace operation fails to match any documents in a collection, it does not make any changes. Replace operations can be configured to perform -an :doc:`upsert ` which +an :doc:`upsert ` which attempts to perform the replacement, but if no documents are matched, it inserts a new document with the specified fields and values. diff --git a/source/crud/update/replace.txt b/source/crud/update/replace.txt new file mode 100644 index 000000000..741b2a854 --- /dev/null +++ b/source/crud/update/replace.txt @@ -0,0 +1,21 @@ +.. _node-replace: + +================= +Replace Documents +================= + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example, node.js, write, add data, change + +Overview +-------- + +In this guide, you can learn how to use {+driver-short+} to perform a replace +operation on a document in a MongoDB collection. A replace operation performs +differently than an update operation. An update operation +modifies only the specified fields in a target document. A replace operation removes *all* fields +in the target document and replaces them with new ones. \ No newline at end of file diff --git a/source/data-formats.txt b/source/data-formats.txt new file mode 100644 index 000000000..4a0c516fd --- /dev/null +++ b/source/data-formats.txt @@ -0,0 +1,35 @@ +.. _node-data-formats: + +======================== +Specialized Data Formats +======================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: bson, uuid, date, time + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + BSON + Time Series Data + +Overview +-------- + +You can use several types of specialized data formats in your {+driver-short+} +application. To learn how to work with these data formats, see the following +sections: + +- Learn how to work with BSON documents in the :ref:`node-bson` guide +- Learn how to work with time series data in the :ref:`node-time-series` guide \ No newline at end of file diff --git a/source/data-formats/bson.txt b/source/data-formats/bson.txt new file mode 100644 index 000000000..2e76a802b --- /dev/null +++ b/source/data-formats/bson.txt @@ -0,0 +1,25 @@ +.. _node-bson-control: +.. _node-bson: + +==== +BSON +==== + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +In this guide, you can learn how to create BSON documents, read BSON from a file, +and write BSON to a file by using {+driver-short+}. + +**BSON**, or Binary JSON, is the data format that MongoDB uses to organize +and store data. This data format includes all JSON data structure types and +adds support for types including dates, different size integers, ObjectIds, and +binary data. \ No newline at end of file diff --git a/source/fundamentals/time-series.txt b/source/data-formats/time-series.txt similarity index 95% rename from source/fundamentals/time-series.txt rename to source/data-formats/time-series.txt index db1789766..6668a7d77 100644 --- a/source/fundamentals/time-series.txt +++ b/source/data-formats/time-series.txt @@ -1,3 +1,5 @@ +.. _node-time-series: + =========== Time Series =========== @@ -39,7 +41,7 @@ querying time series data. For more information on querying data in the MongoDB Node.js driver, see the following resources: -- :ref:`Guide On Read Operations ` +- :ref:`Guide On Read Operations ` - :ref:`Guide On Aggregation ` .. note:: Window Functions diff --git a/source/fundamentals/bson.txt b/source/fundamentals/bson.txt deleted file mode 100644 index 145f875b4..000000000 --- a/source/fundamentals/bson.txt +++ /dev/null @@ -1,31 +0,0 @@ -.. _node-bson-control: - -============= -BSON Settings -============= - -.. meta:: - :description: Configure BSON serialization settings in your application with the MongoDB Node.js Driver, including handling undefined values and UTF-8 validation. - -.. toctree:: - :caption: BSON settings - - Undefined Values - UTF-8 Validation - -.. contents:: On this page - :local: - :backlinks: none - :depth: 1 - :class: singlecol - -Overview --------- - -Learn how to configure your application's BSON serialization settings. -The guides in this section describe the following topics: - -- :ref:`Undefined Values `: Control how the - driver serializes undefined values -- :ref:`UTF-8 Validation `: Enable or disable - the UTF-8 validation feature diff --git a/source/fundamentals/crud.txt b/source/fundamentals/crud.txt deleted file mode 100644 index daa80f8aa..000000000 --- a/source/fundamentals/crud.txt +++ /dev/null @@ -1,57 +0,0 @@ -.. _node-crud-landing: - -=============== -CRUD Operations -=============== - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :description: Learn how to perform create, read, update, and delete (CRUD) operations to work with the data stored in MongoDB by using the Node.js driver. - :keywords: node.js - -.. toctree:: - :caption: CRUD Operations - - Read - Write - Query - Compound Operations - Operations on Replica Sets - -CRUD (Create, Read, Update, Delete) operations allow you to work with -the data stored in MongoDB. - -The CRUD operation documentation is categorized in two sections: - -- :doc:`Read Operations ` find and return - documents stored within your MongoDB database. -- :doc:`Write Operations ` insert, modify, - or delete documents in your MongoDB database. - -Some operations combine aspects of read and write operations. See our -guide on :doc:`compound operations ` -to learn more about these hybrid methods. - -Compatibility -------------- - -.. |page-topic| replace:: perform CRUD operations -.. |link-topic-ing| replace:: performing CRUD operations in the Atlas UI - -.. |atlas-url| replace:: :atlas:`Create, View, Update, and Delete Documents ` - -.. include:: /includes/fact-atlas-compatible.rst -.. include:: /includes/fact-atlas-link.rst - -.. note:: - - To learn more about performing CRUD operations, see the following posts on the `MongoDB - Developer Hub `__: - - - Learn how to apply `CRUD Operations `__ - with an example scenario. - - Analyze data in MongoDB Atlas using the `Aggregation Pipeline `__. - diff --git a/source/fundamentals/crud/read-operations.txt b/source/fundamentals/crud/read-operations.txt deleted file mode 100644 index 749c06a20..000000000 --- a/source/fundamentals/crud/read-operations.txt +++ /dev/null @@ -1,38 +0,0 @@ -.. _node-read-operations: - -=============== -Read Operations -=============== - -.. meta:: - :description: Learn about the commands for running MongoDB read operations by using the {+driver-long+}. - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: code example, node.js, sample dataset - -.. toctree:: - :caption: Read Operations - - Retrieve Data - Access Data from a Cursor - Distinct Values - Sort Results - Skip Returned Results - Limit Returned Results - Specify Fields to Return - Search Geospatially - Search Text - -- :doc:`/fundamentals/crud/read-operations/retrieve` -- :doc:`/fundamentals/crud/read-operations/cursor` -- :doc:`/fundamentals/crud/read-operations/distinct` -- :doc:`/fundamentals/crud/read-operations/sort` -- :doc:`/fundamentals/crud/read-operations/skip` -- :doc:`/fundamentals/crud/read-operations/limit` -- :doc:`/fundamentals/crud/read-operations/project` -- :doc:`/fundamentals/crud/read-operations/geo` -- :doc:`/fundamentals/crud/read-operations/text` diff --git a/source/fundamentals/crud/write-operations.txt b/source/fundamentals/crud/write-operations.txt index 018d07b71..18b3fd807 100644 --- a/source/fundamentals/crud/write-operations.txt +++ b/source/fundamentals/crud/write-operations.txt @@ -17,7 +17,6 @@ Write Operations Upsert Bulk Operations -- :doc:`/fundamentals/crud/write-operations/insert` - :doc:`/fundamentals/crud/write-operations/pkFactory` - :doc:`/fundamentals/crud/write-operations/delete` - :doc:`/fundamentals/crud/write-operations/modify` diff --git a/source/get-started.txt b/source/get-started.txt new file mode 100644 index 000000000..c9de8be9a --- /dev/null +++ b/source/get-started.txt @@ -0,0 +1,229 @@ +.. _node-get-started: + +============================ +Getting Started with Node.js +============================ + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :description: Learn how to create an app to connect to MongoDB deployment by using the Node.js driver. + :keywords: node.js + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Overview +-------- + +This guide shows you how to create an application that uses the +{+driver-long+} to connect to a MongoDB cluster hosted on MongoDB Atlas. If +you prefer to connect to MongoDB using a different driver or programming +language, see our :driver:`list of official drivers <>`. + +The {+driver-short+} is a library of functions that you can use to connect +to and communicate with MongoDB. + +MongoDB Atlas is a fully managed cloud database service that hosts your +MongoDB deployments. You can create your own free (no credit card +required) MongoDB Atlas deployment by following the steps in this guide. + +Follow the steps in this guide to connect a sample Node.js application to +a MongoDB Atlas deployment. + +.. _node-quick-start-download-and-install: +.. _node-get-started-download-and-install: + +Download and Install +-------------------- + +.. procedure:: + :style: connected + + .. step:: Install Node and npm + + Ensure you have Node.js {+min-node-version+} or later and + npm (Node Package Manager) installed in your development environment. + + For information on how to install Node.js and npm, see + `downloading and installing Node.js and npm `__. + + .. step:: Create a Project Directory + + In your shell, run the following command to create a + directory called ``node_quickstart`` for this project: + + .. code-block:: bash + + mkdir node_quickstart + + Run the following command to navigate into the project + directory: + + .. code-block:: bash + + cd node_quickstart + + Run the following command to initialize your Node.js project: + + .. code-block:: bash + + npm init -y + + When this command successfully completes, you have a ``package.json`` + file in your ``node_quickstart`` directory. + + + .. step:: Install the Node.js Driver + + Run the following command in your shell to install + the driver in your project directory: + + .. code-block:: bash + + npm install mongodb@{+version+} + + This command performs the following actions: + + - Downloads the ``mongodb`` package and the dependencies it requires + - Saves the package in the ``node_modules`` directory + - Records the dependency information in the ``package.json`` file + +After you complete these steps, you have Node.js and npm installed +and a new project directory with the driver dependencies installed. + +.. include:: /includes/quick-start/troubleshoot.rst + +.. _node-quick-start-create-deployment: +.. _node-get-started-create-deployment: + +Create a MongoDB Deployment +--------------------------- + +You can create a free tier MongoDB deployment on MongoDB Atlas +to store and manage your data. MongoDB Atlas hosts and manages +your MongoDB database in the cloud. + +.. procedure:: + :style: connected + + .. step:: Create a Free MongoDB deployment on Atlas + + Complete the :atlas:`Get Started with Atlas ` + guide to set up a new Atlas account and load sample data into a new free + tier MongoDB deployment. + + .. step:: Save your Credentials + + After you create your database user, save that user's + username and password to a safe location for use in an upcoming step. + +After you complete these steps, you have a new free tier MongoDB +deployment on Atlas, database user credentials, and sample data loaded +in your database. + +.. include:: /includes/quick-start/troubleshoot.rst + +.. _node-quick-start-connect-to-mongodb: +.. _node-get-started-connect-to-mongodb: + +Connect to MongoDB +------------------ + +.. procedure:: + :style: connected + + .. step:: Create your Node.js Application + + Create a file to contain your application called ``index.js`` in your + ``node_quickstart`` project directory. + + Copy and paste the following code into the ``index.js`` file: + + .. code-block:: js + + const { MongoClient } = require("mongodb"); + + // Replace the uri string with your connection string. + const uri = ""; + + const client = new MongoClient(uri); + + async function run() { + try { + const database = client.db('sample_mflix'); + const movies = database.collection('movies'); + + // Query for a movie that has the title 'Back to the Future' + const query = { title: 'Back to the Future' }; + const movie = await movies.findOne(query); + + console.log(movie); + } finally { + // Ensures that the client will close when you finish/error + await client.close(); + } + } + run().catch(console.dir); + + .. step:: Assign the Connection String + + Replace the ```` placeholder with the + connection string that you copied from the :ref:`node-quick-start-connection-string` + step of this guide. + + .. step:: Run your Node.js Application + + In your shell, run the following command to start this application: + + .. code-block:: none + + node index.js + + The output includes details of the retrieved movie document: + + .. code-block:: none + + { + _id: ..., + plot: 'A young man is accidentally sent 30 years into the past...', + genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ], + ... + title: 'Back to the Future', + ... + } + + If you encounter an error or see no output, check whether you specified the + proper connection string in the ``index.js`` file, and that you loaded the + sample data. + +After you complete these steps, you have a working application that +uses the driver to connect to your MongoDB deployment, runs a query on +the sample data, and prints out the result. + +.. include:: /includes/quick-start/troubleshoot.rst + +.. _node-quick-start-next-steps: +.. _node-get-started-next-steps: + +Next Steps +---------- + +Congratulations on completing the quick start tutorial! + +In this tutorial, you created a Node.js application that +connects to a MongoDB deployment hosted on MongoDB Atlas +and retrieves a document that matches a query. + +Learn more about the {+driver-long+} from the following resources: + +- Discover how to perform read and write operations in the + :ref:`CRUD Operations ` section. + +- See examples of frequently-used operations in the + :ref:`Usage Examples ` section. \ No newline at end of file diff --git a/source/index.txt b/source/index.txt index 7cc4d3878..ae549854d 100644 --- a/source/index.txt +++ b/source/index.txt @@ -16,19 +16,19 @@ MongoDB Node Driver :titlesonly: :maxdepth: 1 - Quick Start - Quick Reference - What's New - Usage Examples - Fundamentals - Aggregation Tutorials + Get Started + Connect + CRUD Operations + Aggregation + Data Formats + Indexes + Run a Database Command + Monitoring and Logging + Security + Reference + Typescript API Documentation <{+api+}> - FAQ - Connection Troubleshooting Issues & Help - Compatibility - Upgrade - Release Notes View the Source Introduction @@ -38,88 +38,83 @@ Welcome to the documentation site for the official {+driver-long+}. You can add the driver to your application to work with MongoDB in JavaScript or TypeScript. For more information about downloading and installing the {+driver-short+}, see -:ref:`Download and Install ` in the -Quick Start guide. +:ref:`Download and Install ` in the +Get Started guide. You can connect using the {+driver-short+} for deployments hosted in the following environments: .. include:: /includes/fact-environments.rst -Quick Start +Get Started ----------- Learn how to establish a connection to MongoDB Atlas and begin -working with data in the step-by-step :doc:`Quick Start `. +working with data in the step-by-step :doc:`Get Started ` tutorial. -Quick Reference ---------------- +Connect to MongoDB +------------------ -See driver syntax examples for common MongoDB commands in the -:ref:`Quick Reference ` section. +Learn how to create and configure a connection to a MongoDB deployment in the +:ref:`` section. -What's New ----------- +Read and Write Data +------------------- -For a list of new features and changes in each version, see the -:ref:`What's New ` section. +Learn how to find, update, and delete data in the :ref:`` section. -Usage Examples --------------- +Transform Your Data with Aggregation +------------------------------------- -For fully runnable code snippets and explanations for common -methods, see the :doc:`Usage Examples ` section. +Learn how to use the {+driver-short+} to perform aggregation operations in the +:ref:`` section. -Fundamentals +Data Formats ------------ -.. include:: /includes/fundamentals-sections.rst +Learn how to work with BSON and other data formats in the +:ref:`` section. -Aggregation Tutorials ---------------------- +Optimize Queries with Indexes +----------------------------- -For step-by-step explanations of common -aggregation tasks, see the :ref:`node-aggregation-tutorials-landing` -section. +Learn how to work with common types of indexes in the :ref:`` section. -API ---- +Run a Database Command +---------------------- -For detailed information about classes and methods in the MongoDB -Node.js driver, see the `{+driver-long+} API documentation -<{+api+}>`__. +Learn how to run a database command in the :ref:`` section. -FAQ ---- +Monitoring and Logging +---------------------- -For answers to commonly asked questions about the MongoDB -Node.js Driver, see the :doc:`Frequently Asked Questions (FAQ) ` -section. +Learn how to monitor changes to your application and write them to logs in the +:ref:`` section. -Connection Troubleshooting --------------------------- +Secure Your Data +---------------- -For solutions to issues you might encounter when using the driver to connect to -a MongoDB deployment, see the :ref:`node-connection-troubleshooting` section. +Learn about ways you can authenticate your application and encrypt your data in +the :ref:`` section. -Issues & Help -------------- +Reference +--------- -Learn how to report bugs, contribute to the driver, and to find help in the -:doc:`Issues & Help ` section. +Find more information about {+driver-short+} versions, compatibility, and third-party tools in the +:doc:`Reference ` section. -Compatibility -------------- +API Documentation +----------------- -For the compatibility tables that show the recommended {+driver-short+} -version for each {+mdb-server+} version, see the -:doc:`Compatibility ` section. +For detailed information about classes and methods in the MongoDB +Node.js driver, see the `{+driver-long+} API documentation +<{+api+}>`__. -Upgrade Driver Versions ------------------------ +Issues & Help +------------- -Learn what changes you must make to your application to upgrade -driver versions in the :ref:`` section. +Learn how to report bugs, contribute to the driver, and to find help in the +:doc:`Issues & Help ` section. Related Tools and Libraries --------------------------- diff --git a/source/fundamentals/indexes.txt b/source/indexes.txt similarity index 99% rename from source/fundamentals/indexes.txt rename to source/indexes.txt index a01303115..fe9762ee1 100644 --- a/source/fundamentals/indexes.txt +++ b/source/indexes.txt @@ -1,4 +1,5 @@ .. _node-fundamentals-indexes: +.. _node-indexes: ======= Indexes @@ -259,7 +260,7 @@ MongoDB supports queries of geospatial coordinate data using **2dsphere indexes**. With a 2dsphere index, you can query the geospatial data for inclusion, intersection, and proximity. For more information on querying geospatial data with the MongoDB Node.js driver, read our -:doc:`Search Geospatial ` guide. +:doc:`Search Geospatial ` guide. To create a 2dsphere index, you must specify a field that contains only **GeoJSON objects**. For more details on this type, see the MongoDB diff --git a/source/monitoring-and-logging.txt b/source/monitoring-and-logging.txt new file mode 100644 index 000000000..f3e5e66cc --- /dev/null +++ b/source/monitoring-and-logging.txt @@ -0,0 +1,24 @@ +.. _node-monitoring-logging: + +====================== +Monitoring and Logging +====================== + +.. facet:: + :name: programming_language + :values: python + +.. 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/usage-examples/changeStream.txt b/source/monitoring-and-logging/change-streams.txt similarity index 93% rename from source/usage-examples/changeStream.txt rename to source/monitoring-and-logging/change-streams.txt index 7d72a9479..e16fd4226 100644 --- a/source/usage-examples/changeStream.txt +++ b/source/monitoring-and-logging/change-streams.txt @@ -1,14 +1,36 @@ .. _node-usage-watch: +.. _node-change-streams: -================= -Watch for Changes -================= +==================== +Monitor Data Changes +==================== .. meta:: :description: Monitor changes in MongoDB using the watch() method in the MongoDB Node.js Driver on collections, databases, or clients to open change streams and handle change events. .. default-domain:: mongodb +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: watch, code example + +Overview +-------- + +In this guide, you can learn how to use a **change stream** to monitor real-time +changes to your database. A change stream is a {+mdb-server+} feature that +allows your application to subscribe to data changes on a collection, database, +or deployment. + Open a Change Stream -------------------- diff --git a/source/fundamentals/logging.txt b/source/monitoring-and-logging/logging.txt similarity index 100% rename from source/fundamentals/logging.txt rename to source/monitoring-and-logging/logging.txt diff --git a/source/fundamentals/monitoring.txt b/source/monitoring-and-logging/monitoring.txt similarity index 97% rename from source/fundamentals/monitoring.txt rename to source/monitoring-and-logging/monitoring.txt index cd132fa24..3d329071c 100644 --- a/source/fundamentals/monitoring.txt +++ b/source/monitoring-and-logging/monitoring.txt @@ -1,3 +1,5 @@ +.. _node-monitoring: + ========== Monitoring ========== diff --git a/source/quick-start.txt b/source/quick-start.txt deleted file mode 100644 index 0ebfed6a7..000000000 --- a/source/quick-start.txt +++ /dev/null @@ -1,45 +0,0 @@ -.. _node-quickstart: - -======================= -Node Driver Quick Start -======================= - -.. facet:: - :name: genre - :values: tutorial - -.. meta:: - :description: Learn how to create an app to connect to MongoDB deployment by using the Node.js driver. - :keywords: node.js - -.. contents:: On this page - :local: - :backlinks: none - :depth: 1 - :class: singlecol - -.. toctree:: - - Download & Install - Create a Deployment - Create a Connection String - Connect to MongoDB - Next Steps - -Overview --------- - -This guide shows you how to create an application that uses the -{+driver-long+} to connect to a MongoDB cluster hosted on MongoDB Atlas. If -you prefer to connect to MongoDB using a different driver or programming -language, see our :driver:`list of official drivers <>`. - -The {+driver-short+} is a library of functions that you can use to connect -to and communicate with MongoDB. - -MongoDB Atlas is a fully managed cloud database service that hosts your -MongoDB deployments. You can create your own free (no credit card -required) MongoDB Atlas deployment by following the steps in this guide. - -Follow the steps in this guide to connect a sample Node.js application to -a MongoDB Atlas deployment. diff --git a/source/reference.txt b/source/reference.txt new file mode 100644 index 000000000..937e7fe88 --- /dev/null +++ b/source/reference.txt @@ -0,0 +1,14 @@ +.. _node-reference: + +========== +Reference +========== + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Release Notes + Compatibility + Upgrade Guides + Quick Reference diff --git a/source/compatibility.txt b/source/reference/compatibility.txt similarity index 100% rename from source/compatibility.txt rename to source/reference/compatibility.txt diff --git a/source/quick-reference.txt b/source/reference/quick-reference.txt similarity index 99% rename from source/quick-reference.txt rename to source/reference/quick-reference.txt index 000b93190..6cb1c5c21 100644 --- a/source/quick-reference.txt +++ b/source/reference/quick-reference.txt @@ -39,7 +39,7 @@ Compatibility | | `API Documentation <{+api+}/classes/Collection.html#findOne>`__ | :ref:`Usage Example ` - | :ref:`Fundamentals ` + | :ref:`Query Operations ` - .. io-code-block:: :copyable: true diff --git a/source/whats-new.txt b/source/reference/release-notes.txt similarity index 99% rename from source/whats-new.txt rename to source/reference/release-notes.txt index fa6215295..1701e138c 100644 --- a/source/whats-new.txt +++ b/source/reference/release-notes.txt @@ -1,8 +1,9 @@ .. _node-whats-new: +.. _node-release-notes: -========== -What's New -========== +============= +Release Notes +============= .. contents:: On this page :local: diff --git a/source/upgrade.txt b/source/reference/upgrade.txt similarity index 100% rename from source/upgrade.txt rename to source/reference/upgrade.txt diff --git a/source/fundamentals/run-command.txt b/source/run-command.txt similarity index 100% rename from source/fundamentals/run-command.txt rename to source/run-command.txt diff --git a/source/security.txt b/source/security.txt new file mode 100644 index 000000000..ec4c2872c --- /dev/null +++ b/source/security.txt @@ -0,0 +1,34 @@ +.. _node-security: + +========= +Security +========= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: ldap, encryption, principal, tls, authorize, boto, ecs, aws + :description: Learn how to use {+driver-short+} to secure your data. + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Authentication + In-Use Encryption + TLS Security Protocol + SOCKS Proxy + +Overview +-------- + +MongoDB supports multiple mechanisms that you can use to authenticate your application. +This page contains code examples that show each of these mechanisms. \ No newline at end of file diff --git a/source/fundamentals/authentication.txt b/source/security/authentication.txt similarity index 76% rename from source/fundamentals/authentication.txt rename to source/security/authentication.txt index 2a6c3ef6f..0ec2bd2c9 100644 --- a/source/fundamentals/authentication.txt +++ b/source/security/authentication.txt @@ -1,4 +1,5 @@ .. _node-authentication-mechanisms: +.. _node-authentication: ============== Authentication @@ -11,8 +12,8 @@ Authentication .. toctree:: - Authentication - Enterprise Authentication + Authentication + Enterprise Authentication Overview -------- @@ -20,7 +21,7 @@ Overview These guides show you how to authenticate to a MongoDB instance using the Node.js driver. -The :doc:`Authentication Mechanisms ` guide contains +The :doc:`Authentication Mechanisms ` guide contains sample connection code using each authentication mechanism supported in the MongoDB Community Edition which includes: @@ -32,7 +33,7 @@ MongoDB Community Edition which includes: - ``X.509`` The :doc:`Enterprise Authentication Mechanisms -` guide contains sample +` guide contains sample connection code using authentication mechanisms available only in MongoDB Enterprise Edition which includes: diff --git a/source/fundamentals/authentication/enterprise-mechanisms.txt b/source/security/authentication/enterprise-mechanisms.txt similarity index 100% rename from source/fundamentals/authentication/enterprise-mechanisms.txt rename to source/security/authentication/enterprise-mechanisms.txt diff --git a/source/fundamentals/authentication/mechanisms.txt b/source/security/authentication/mechanisms.txt similarity index 100% rename from source/fundamentals/authentication/mechanisms.txt rename to source/security/authentication/mechanisms.txt diff --git a/source/fundamentals/encrypt-fields.txt b/source/security/encrypt-fields.txt similarity index 100% rename from source/fundamentals/encrypt-fields.txt rename to source/security/encrypt-fields.txt diff --git a/source/fundamentals/connection/socks.txt b/source/security/socks.txt similarity index 99% rename from source/fundamentals/connection/socks.txt rename to source/security/socks.txt index 44b650a1b..ce3623dde 100644 --- a/source/fundamentals/connection/socks.txt +++ b/source/security/socks.txt @@ -1,4 +1,5 @@ .. _node-connect-socks: +.. _node-socks: =========================== Enable SOCKS5 Proxy Support diff --git a/source/fundamentals/connection/tls.txt b/source/security/tls.txt similarity index 99% rename from source/fundamentals/connection/tls.txt rename to source/security/tls.txt index 0a922e0de..e80eaff1e 100644 --- a/source/fundamentals/connection/tls.txt +++ b/source/security/tls.txt @@ -1,4 +1,5 @@ .. _node-connect-tls: +.. _node-tls: ========================== Enable TLS on a Connection diff --git a/source/fundamentals/typescript.txt b/source/typescript.txt similarity index 99% rename from source/fundamentals/typescript.txt rename to source/typescript.txt index 872c23de9..e40f58b0b 100644 --- a/source/fundamentals/typescript.txt +++ b/source/typescript.txt @@ -1,4 +1,5 @@ -.. node-fundamentals-typescript: +.. _node-fundamentals-typescript: +.. _node-typescript: ========== TypeScript @@ -204,7 +205,7 @@ To learn more about the limitations of dot notation in the :ref:`` section. -.. typescript-working-with-id: +.. _node-typescript-working-with-id: Working with the _id Field -------------------------- diff --git a/source/usage-examples.txt b/source/usage-examples.txt index 7b44da38d..f3c6d6e6b 100644 --- a/source/usage-examples.txt +++ b/source/usage-examples.txt @@ -59,7 +59,7 @@ can :guides:`import the sample dataset into a local MongoDB instance Once you have imported the dataset, you can copy and paste a usage example into your development environment of choice. You can follow the -:doc:`quick start guide ` to learn more about getting +:doc:`get started guide ` to learn more about getting started with Node.js, npm, and the Node.js driver. Once you've copied a usage example, you must edit one line to get the example running with your instance of MongoDB: @@ -121,9 +121,10 @@ Available Usage Examples - :doc:`Insert Operations ` - :doc:`Update Operations ` - :doc:`Delete Operations ` -- :doc:`Count Documents ` - :doc:`Retrieve Distinct Values of a Field ` - :doc:`Run a Command ` -- :doc:`Watch for Changes ` - :doc:`Perform Bulk Operations ` - :doc:`Perform a Transaction ` + +.. - :doc:`Count Documents ` +.. - :doc:`Watch for Changes ` From 818ca120b90738d4072fd0e6904f911b008c3039 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Wed, 30 Apr 2025 09:47:30 -0400 Subject: [PATCH 2/4] include bson page --- source/data-formats/bson.txt | 160 +++++++++++++++++++++++++++++++++-- 1 file changed, 153 insertions(+), 7 deletions(-) diff --git a/source/data-formats/bson.txt b/source/data-formats/bson.txt index 2e76a802b..28726bc22 100644 --- a/source/data-formats/bson.txt +++ b/source/data-formats/bson.txt @@ -1,9 +1,9 @@ .. _node-bson-control: .. _node-bson: -==== -BSON -==== +=================== +Work with BSON Data +=================== .. default-domain:: mongodb @@ -17,9 +17,155 @@ Overview -------- In this guide, you can learn how to create BSON documents, read BSON from a file, -and write BSON to a file by using {+driver-short+}. +and write BSON to a file by using the {+driver-short+}. **BSON**, or Binary JSON, is the data format that MongoDB uses to organize -and store data. This data format includes all JSON data structure types and -adds support for types including dates, different size integers, ObjectIds, and -binary data. \ No newline at end of file +and store data. You can use BSON documents in your {+language+} application +by importing the BSON package. + +The code samples in this guide use the following BSON document as an example: + +.. code-block:: none + + { + "address" : { + "street" : "Pizza St", + "zipcode" : "10003" + }, + "coord" : [-73.982419, 41.579505], + "cuisine" : "Pizza", + "name" : "Mongo's Pizza" + } + +.. note:: Use the {+driver-short+}'s BSON package + + We recommend that you use the BSON package that is bundled with the driver to avoid + compatibility issues with other BSON packages. You can import the {+driver-short+}'s + BSON package with the following import statement: + + .. code-block:: js + + import { BSON } from 'mongodb'; + +BSON Data Types +--------------- + +BSON supports all JSON data structure types and adds support for types including +dates, different size integers, ``ObjectId``, and binary data. For a complete list of +supported types, see the :manual:`BSON Types ` page in the +{+mdb-server+} Manual. + +Universally Unique IDs (UUIDs) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The {+driver-short+} supports UUIDs by using the BSON Binary subclass ``UUID``. You +can create a ``UUID`` object by using the ``UUID()`` constructor. The following code +example generates a random UUID: + +.. code-block:: javascript + + import { UUID } from 'mongodb'; + + const myUuid = new UUID(); + +Create a BSON Document +---------------------- + +You can create a BSON document by using the same notation you use to create an +object in {+language+}. The {+driver-short+} automatically converts {+language+} objects +into BSON documents when inserting them into a collection. + +The following example creates a BSON document that +represents the preceding sample BSON document: + +.. code-block:: javascript + + const document = { + "address": { + "street": "Pizza St", + "zipcode": "10003", + }, + "coord": [-73.982419, 41.579505], + "cuisine": "Pizza", + "name": "Mongo's Pizza", + } + +Change a BSON Document +---------------------- + +You can modify the contents of a BSON document by using the same notation you use to modify +an object in {+language+}. The following example makes three changes to the previous +BSON document: + +1. Adds a new field, ``restaurant_id``, with the value ``12345`` +#. Removes the ``cuisine`` field +#. Sets the value of the ``name`` field to ``"Mongo's Pizza Place"`` + +.. code-block:: javascript + + document.restaurant_id = "12345"; + delete document.cuisine; + document.name = "Mongo's Pizza Place"; + +Write BSON to a File +-------------------- + +To write BSON data to a file, import the file system module and open the output file. +Then, write each document to the output file. Ensure that documents are encoded in BSON +format by using the ``BSON.serialize()`` method. + +The following example writes the sample BSON document to ``file.bson``: + +.. code-block:: javascript + + import fs from 'fs/promises'; // Import the file system module + import { BSON } from 'mongodb'; // Import the BSON package + + // Create a BSON object + const bsonData = BSON.serialize(result); + + // Write the BSON data to a file + await fs.writeFile('file.bson', bsonData); + console.log('BSON data written to file.bson'); + +Read BSON from a File +--------------------- + +To read BSON documents from a file, open a file in read mode. Then, decode the documents +from BSON format as you read them by using the ``BSON.deserialize()`` method. + +The following example reads the sample BSON document from ``file.bson``: + +.. io-code-block:: + :copyable: true + + .. input:: + :language: javascript + + import fs from 'fs/promises'; // Import the file system module + import { BSON } from 'mongodb'; // Import the BSON package + + // Read the BSON data from a file + const data = await fs.readFile('file.bson'); + const document = BSON.deserialize(data); + console.log(document); + + .. output:: + :visible: false + + { + _id: new ObjectId('67e1823d0d63bfdf87e8928e'), + address: { street: 'Pizza St', zipcode: '10003' }, + coord: [ -73.982419, 41.579505 ], + cuisine: 'Pizza', + name: "Mongo's Pizza" + } + +API Documentation +----------------- + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- `BSON <{+api+}/modules/BSON.html>`__ +- `UUID <{+api+}/classes/BSON.UUID.html>`__ From 597bb72a3405e3681040ccfae6f8c9d75845cae8 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Wed, 30 Apr 2025 09:48:54 -0400 Subject: [PATCH 3/4] aggregation desc --- source/aggregation.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/source/aggregation.txt b/source/aggregation.txt index 7043a839c..c4f2504e4 100644 --- a/source/aggregation.txt +++ b/source/aggregation.txt @@ -11,7 +11,6 @@ Aggregation .. meta:: :keywords: node.js, code example, runnable app - :description: Learn to use aggregation operations in the MongoDB Node.js Driver to create pipelines for data transformation and summarization. .. contents:: On this page :local: From 161fe1639046af196a9ecc7e5b1eafa61fbe585d Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Wed, 30 Apr 2025 10:05:22 -0400 Subject: [PATCH 4/4] LM feedback --- config/redirects | 2 +- source/archive-reference-files/collations.txt | 318 ------------------ .../quick-start/connect-to-mongodb.txt | 81 ----- .../create-a-connection-string.txt | 63 ---- .../quick-start/create-a-deployment.txt | 32 -- .../quick-start/download-and-install.txt | 65 ---- .../quick-start/facets.toml | 3 - .../quick-start/next-steps.txt | 22 -- .../connection-options/connection-pools.txt | 257 +++++++++++++- source/connect/connection-targets.txt | 95 +++++- 10 files changed, 348 insertions(+), 590 deletions(-) delete mode 100644 source/archive-reference-files/collations.txt delete mode 100644 source/archive-reference-files/quick-start/connect-to-mongodb.txt delete mode 100644 source/archive-reference-files/quick-start/create-a-connection-string.txt delete mode 100644 source/archive-reference-files/quick-start/create-a-deployment.txt delete mode 100644 source/archive-reference-files/quick-start/download-and-install.txt delete mode 100644 source/archive-reference-files/quick-start/facets.toml delete mode 100644 source/archive-reference-files/quick-start/next-steps.txt diff --git a/config/redirects b/config/redirects index 73b0fb329..1a1749618 100644 --- a/config/redirects +++ b/config/redirects @@ -23,7 +23,7 @@ raw: ${prefix}/stable -> ${base}/current/ [*-v5.5]: ${prefix}/${version}/fundamentals/run-command/ -> ${base}/${version}/usage-examples/command/ [*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/change-a-document/ -> ${base}/${version}/fundamentals/crud/write-operations/modify/ -[*-v6.0)]: ${prefix}/${version}/fundamentals/connection/socks/ -> ${base}/${version}/ +[*-v6.0]: ${prefix}/${version}/fundamentals/connection/socks/ -> ${base}/${version}/ [*-master]: ${prefix}/${version}/quick-start/download-and-install/ -> ${base}/${version}/get-started/ [*-master]: ${prefix}/${version}/quick-start/create-a-deployment/ -> ${base}/${version}/get-started/ diff --git a/source/archive-reference-files/collations.txt b/source/archive-reference-files/collations.txt deleted file mode 100644 index 2ad831cbd..000000000 --- a/source/archive-reference-files/collations.txt +++ /dev/null @@ -1,318 +0,0 @@ -.. _node-fundamentals-collations: -.. _node-collations: - -========== -Collations -========== - -.. meta:: - :description: Learn how to use collations to apply specific sorting rules for string operations based on language and locale preferences with the MongoDB Node.js Driver. - -.. default-domain:: mongodb - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -*Collations are available in MongoDB 3.4 and later.* - --------- -Overview --------- - -This guide shows you how to use **collations**, a set of sorting rules, to -run operations using string ordering for specific languages and locales (a -community or region that shares common language idioms). - -MongoDB sorts strings using *binary collation* by default. This collation -method uses the `ASCII standard `_ -character values to compare and order strings. Languages and locales -have specific character ordering conventions that differ from the ASCII -standard. - -For example, in Canadian French, the right-most accented character determines -the ordering for strings when the other characters are the same. Consider the -following French words: **cote**, **coté**, **côte**, and **côté**. - -MongoDB sorts them in the following order using the default binary collation: - -.. code-block:: none - - cote - coté - côte - côté - -MongoDB sorts them in the following order using the Canadian French collation: - -.. code-block:: none - - cote - côte - coté - côté - ------ -Usage ------ - -You can specify a collation when you create a new collection or new index. You -can also specify a collation for :doc:`CRUD operations ` -and aggregations. - -When you create a new collection with a collation, you define the default -collation for any of the :manual:`operations that support collation -` called on that -collection. You can override the collation for an operation by specifying a -different one. - -.. note:: - - Currently, you cannot create a collation on an existing collection. To use - collations with an existing collection, create an index with the collation - and specify the same collation in your operations on it. - -When you create an index with a collation, you specify the sort order for -operations that use that index. To use the collation in the index, you -must provide a matching collation in the operation, and the operation must -use the index. While most index types support collation, the following -types support only binary comparison: - -- :manual:`text ` -- :manual:`2d ` -- :manual:`geoHaystack ` - -Collation Parameters -~~~~~~~~~~~~~~~~~~~~ - -The collation object contains the following parameters: - -.. code-block:: javascript - - collation: { - locale: , - caseLevel: , - caseFirst: , - strength: , - numericOrdering: , - alternate: , - maxVariable: , - backwards: - } - -You must specify the ``locale`` field in the collation; all other fields -are optional. For a complete list of supported locales and the default values -for the ``locale`` fields, see :manual:`Supported Languages and Locales -`. -For descriptions of each field, see the :manual:`Collation Document MongoDB -manual entry `. - ------------------- -Collation Examples ------------------- - -Set a Default Collation on a Collection -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -In the following example, we create a new collection called ``souvenirs`` and -assign a default collation with the ``"fr_CA"`` locale. The collation applies -to all :manual:`operations that support collation -` performed on that -collection. - -.. literalinclude:: /code-snippets/collation/collection-collation.js - :language: javascript - :start-after: start collection collation - :end-before: end collection collation - -Any of the operations that support collations automatically apply the collation -defined on the collection. The query below searches the ``souvenirs`` -collection and applies the ``"fr_CA"`` locale collation: - -.. literalinclude:: /code-snippets/collation/collection-auto-collation.js - :language: javascript - :start-after: start auto collation - :end-before: end auto collation - -You can specify a different collation as a parameter in an operation that -supports collations. The following query specifies the ``"is"`` Iceland locale -and ``caseFirst`` optional parameter with the value ``"upper"``: - -.. literalinclude:: /code-snippets/collation/collection-specify-collation.js - :language: javascript - :start-after: start specified collation - :end-before: end specified collation - -Assign a Collation to an Index -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -In the following example, we create a new index on the ``title`` field of -a collection with a collation set to the ``"en_US"`` locale. - -.. literalinclude:: /code-snippets/collation/index-collation.js - :language: javascript - :start-after: start create index collation - :end-before: end create index collation - -The following query uses the index we created: - -.. literalinclude:: /code-snippets/collation/query-index-collation.js - :language: javascript - :start-after: start query index collation - :end-before: end query index collation - -The following queries **do not** use the index that we created. The first -query does not include a collation and the second contains a different -strength value than the collation on the index. - -.. literalinclude:: /code-snippets/collation/query-not-indexed-collation.js - :language: javascript - :start-after: start not indexed collation - :end-before: end not indexed collation - -.. literalinclude:: /code-snippets/collation/query-index-no-collation.js - :language: javascript - :start-after: start index no collation - :end-before: end index no collation - -Collation Query Examples -~~~~~~~~~~~~~~~~~~~~~~~~ - -Operations that read, update, and delete documents from a collection can use -collations. This section includes examples of a selection of these. See the -MongoDB manual for a full list of :manual:`operations that support collation -`. - -find() and sort() Example -````````````````````````` - -The following example calls both ``find()`` and ``sort()`` on a collection -that uses the default binary collation. We use the German collation by -setting the value of the ``locale`` parameter to ``"de"``. - -.. literalinclude:: /code-snippets/collation/find-sort-collation.js - :language: javascript - :start-after: start find sort collation - :end-before: end find sort collation - -findOneAndUpdate() Example -`````````````````````````` - -The following example calls the ``findOneAndUpdate()`` operation on a -collection that uses the default binary collation. The collection contains the -following documents: - -.. code-block:: none - - { "_id" : 1, "first_name" : "Hans" } - { "_id" : 2, "first_name" : "Gunter" } - { "_id" : 3, "first_name" : "Günter" } - { "_id" : 4, "first_name" : "Jürgen" } - -Consider the following ``findOneAndUpdate()`` operation on this collection -which **does not** specify a collation: - -.. literalinclude:: /code-snippets/collation/findOneAndUpdate-default-order-collation.js - :language: javascript - :start-after: start findOneAndUpdate default order collation - :end-before: end findOneAndUpdate default order collation - -Since "Gunter" is the first sorted result when using a binary collation, none -of the documents come lexically before and match the ``$lt`` comparison -operator in the query document. As a result, the operation does not update any -documents. - -Consider the same operation with a collation specified with the locale set to -``de@collation=phonebook``. This locale specifies the ``collation=phonebook`` -option which contains rules for prioritizing proper nouns, identified by -capitalization of the first letter. The ``de@collation=phonebook`` locale and -option sorts characters with umlauts before the same characters without -umlauts. - -.. literalinclude:: /code-snippets/collation/findOneAndUpdate-collation.js - :language: javascript - :start-after: start findOneAndUpdate collation - :end-before: end findOneAndUpdate collation - -Since "Günter" lexically comes before "Gunter" using the -``de@collation=phonebook`` collation specified in ``findOneAndUpdate()``, -the operation returns the following updated document: - -.. code-block:: none - - { lastErrorObject: { updatedExisting: true, n: 1 }, - value: { _id: 3, first_name: 'Günter' }, - ok: 1 } - -findOneAndDelete() Example -`````````````````````````` - -The following example calls the ``findOneAndDelete()`` operation on a -collection that uses the default binary collation and contains the following -documents: - -.. code-block:: none - - { "_id" : 1, "a" : "16" } - { "_id" : 2, "a" : "84" } - { "_id" : 3, "a" : "179" } - -In this example, we set the ``numericOrdering`` collation parameter to ``true`` -to sort numeric strings based on their numerical order instead of their -lexical order. - -.. literalinclude:: /code-snippets/collation/findOneAndDelete-collation.js - :language: javascript - :start-after: start findOneAndDelete collation - :end-before: end findOneAndDelete collation - -After you run the operation above, the collection contains the following -documents: - -.. code-block:: none - - { "_id" : 1, "a" : "16" } - { "_id" : 2, "a" : "84" } - -If you perform the same operation without collation on the original -collection of three documents, it matches documents based on the lexical value -of the strings (``"16"``, ``"84"``, and ``"179"``), and deletes the first -document it finds that matches the query criteria. - -.. literalinclude:: /code-snippets/collation/findOneAndDelete-no-collation.js - :language: javascript - :start-after: start findOneAndDelete no collation - :end-before: end findOneAndDelete no collation - -Since all the documents contain lexical values in the ``a`` field that -match the criteria (greater than the lexical value of ``"100"``), the operation -removes the first result. After you run the operation above, the collection -contains the following documents: - -.. code-block:: none - - { "_id" : 2, "a" : "84" } - { "_id" : 3, "a" : "179" } - -Aggregation Example -``````````````````` - -To use collation with the `aggregate <{+api+}/classes/Collection.html#aggregate>`__ -operation, pass the collation document in the options field, after the -array of pipeline stages. - -The following example shows an aggregation pipeline on a collection that uses -the default binary collation. The aggregation groups the ``first_name`` field, -counts the total number of results in each group, and sorts the results by -the German phonebook (``"de@collation=phonebook"`` locale) order. - -.. note:: - - You can specify only one collation on an aggregation. - -.. literalinclude:: /code-snippets/collation/aggregation-collation.js - :language: javascript - :start-after: start aggregation collation - :end-before: end aggregation collation diff --git a/source/archive-reference-files/quick-start/connect-to-mongodb.txt b/source/archive-reference-files/quick-start/connect-to-mongodb.txt deleted file mode 100644 index 45a2eb228..000000000 --- a/source/archive-reference-files/quick-start/connect-to-mongodb.txt +++ /dev/null @@ -1,81 +0,0 @@ -.. _node-quick-start-connect-to-mongodb: - -================== -Connect to MongoDB -================== - -.. meta:: - :description: Connect to MongoDB using the MongoDB Node.js Driver by creating an application, assigning a connection string, and running a query to retrieve data. - -.. procedure:: - :style: connected - - .. step:: Create your Node.js Application - - Create a file to contain your application called ``index.js`` in your - ``node_quickstart`` project directory. - - Copy and paste the following code into the ``index.js`` file: - - .. code-block:: js - - const { MongoClient } = require("mongodb"); - - // Replace the uri string with your connection string. - const uri = ""; - - const client = new MongoClient(uri); - - async function run() { - try { - const database = client.db('sample_mflix'); - const movies = database.collection('movies'); - - // Query for a movie that has the title 'Back to the Future' - const query = { title: 'Back to the Future' }; - const movie = await movies.findOne(query); - - console.log(movie); - } finally { - // Ensures that the client will close when you finish/error - await client.close(); - } - } - run().catch(console.dir); - - .. step:: Assign the Connection String - - Replace the ```` placeholder with the - connection string that you copied from the :ref:`node-quick-start-connection-string` - step of this guide. - - .. step:: Run your Node.js Application - - In your shell, run the following command to start this application: - - .. code-block:: none - - node index.js - - The output includes details of the retrieved movie document: - - .. code-block:: none - - { - _id: ..., - plot: 'A young man is accidentally sent 30 years into the past...', - genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ], - ... - title: 'Back to the Future', - ... - } - - If you encounter an error or see no output, check whether you specified the - proper connection string in the ``index.js`` file, and that you loaded the - sample data. - -After you complete these steps, you have a working application that -uses the driver to connect to your MongoDB deployment, runs a query on -the sample data, and prints out the result. - -.. include:: /includes/quick-start/troubleshoot.rst diff --git a/source/archive-reference-files/quick-start/create-a-connection-string.txt b/source/archive-reference-files/quick-start/create-a-connection-string.txt deleted file mode 100644 index cc580776c..000000000 --- a/source/archive-reference-files/quick-start/create-a-connection-string.txt +++ /dev/null @@ -1,63 +0,0 @@ -.. _node-quick-start-connection-string: - -========================== -Create a Connection String -========================== - -.. meta:: - :description: Create a connection string for your MongoDB deployment by including the hostname, port, authentication mechanism, and user credentials. - -You can connect to your MongoDB deployment by providing a -**connection URI**, also called a *connection string*, which -instructs the driver on how to connect to a MongoDB deployment -and how to behave while connected. - -The connection string includes the hostname or IP address and -port of your deployment, the authentication mechanism, user credentials -when applicable, and connection options. - -To connect to an instance or deployment not hosted on Atlas, see -:ref:`Other Ways to Connect to MongoDB `. - -.. procedure:: - :style: connected - - .. step:: Find your MongoDB Atlas Connection String - - To retrieve your connection string for the deployment that - you created in the :ref:`previous step `, - log into your Atlas account and navigate to the - :guilabel:`Clusters` section and click the :guilabel:`Connect` button - for your new deployment. - - .. figure:: /includes/figures/atlas_connect.png - :alt: The connect button in the clusters section of the Atlas UI - - Select the :guilabel:`Drivers` option from the :guilabel:`Connect to your application` - section. Then in the :guilabel:`Connecting with MongoDB Driver` - menu, select "Node.js" from the :guilabel:`Driver` selection menu and the version - that best matches the version you installed from the :guilabel:`Version` - selection menu. - - Select the :guilabel:`Password (SCRAM)` authentication mechanism. - - .. step:: Copy your Connection String - - Click the button on the right of the connection string to copy it to - your clipboard as shown in the following screenshot: - - .. figure:: /includes/figures/atlas_connection_copy_string.png - :alt: The connection string copy button in the Atlas UI - - .. step:: Update the Placeholders - - Paste this connection string into a a file in your preferred text editor - and replace the "" and "" placeholders with - your database user's username and password. - - Save this file to a safe location for use in the next step. - -After completing these steps, you have a connection string that -contains your database username and password. - -.. include:: /includes/quick-start/troubleshoot.rst diff --git a/source/archive-reference-files/quick-start/create-a-deployment.txt b/source/archive-reference-files/quick-start/create-a-deployment.txt deleted file mode 100644 index a1fade2f2..000000000 --- a/source/archive-reference-files/quick-start/create-a-deployment.txt +++ /dev/null @@ -1,32 +0,0 @@ -.. _node-quick-start-create-deployment: - -=========================== -Create a MongoDB Deployment -=========================== - -.. meta:: - :description: Set up a free tier MongoDB deployment on Atlas, including creating an account, saving credentials, and loading sample data. - -You can create a free tier MongoDB deployment on MongoDB Atlas -to store and manage your data. MongoDB Atlas hosts and manages -your MongoDB database in the cloud. - -.. procedure:: - :style: connected - - .. step:: Create a Free MongoDB deployment on Atlas - - Complete the :atlas:`Get Started with Atlas ` - guide to set up a new Atlas account and load sample data into a new free - tier MongoDB deployment. - - .. step:: Save your Credentials - - After you create your database user, save that user's - username and password to a safe location for use in an upcoming step. - -After you complete these steps, you have a new free tier MongoDB -deployment on Atlas, database user credentials, and sample data loaded -in your database. - -.. include:: /includes/quick-start/troubleshoot.rst diff --git a/source/archive-reference-files/quick-start/download-and-install.txt b/source/archive-reference-files/quick-start/download-and-install.txt deleted file mode 100644 index 76c22f2c6..000000000 --- a/source/archive-reference-files/quick-start/download-and-install.txt +++ /dev/null @@ -1,65 +0,0 @@ -.. _node-quick-start-download-and-install: - -==================== -Download and Install -==================== - -.. meta:: - :description: Install Node.js and npm, create a project directory, and install the MongoDB Node.js Driver. - -.. procedure:: - :style: connected - - .. step:: Install Node and npm - - Ensure you have Node.js {+min-node-version+} or later and - npm (Node Package Manager) installed in your development environment. - - For information on how to install Node.js and npm, see - `downloading and installing Node.js and npm `__. - - .. step:: Create a Project Directory - - In your shell, run the following command to create a - directory called ``node_quickstart`` for this project: - - .. code-block:: bash - - mkdir node_quickstart - - Run the following command to navigate into the project - directory: - - .. code-block:: bash - - cd node_quickstart - - Run the following command to initialize your Node.js project: - - .. code-block:: bash - - npm init -y - - When this command successfully completes, you have a ``package.json`` - file in your ``node_quickstart`` directory. - - - .. step:: Install the Node.js Driver - - Run the following command in your shell to install - the driver in your project directory: - - .. code-block:: bash - - npm install mongodb@{+version+} - - This command performs the following actions: - - - Downloads the ``mongodb`` package and the dependencies it requires - - Saves the package in the ``node_modules`` directory - - Records the dependency information in the ``package.json`` file - -After you complete these steps, you have Node.js and npm installed -and a new project directory with the driver dependencies installed. - -.. include:: /includes/quick-start/troubleshoot.rst diff --git a/source/archive-reference-files/quick-start/facets.toml b/source/archive-reference-files/quick-start/facets.toml deleted file mode 100644 index 07bd7b7f7..000000000 --- a/source/archive-reference-files/quick-start/facets.toml +++ /dev/null @@ -1,3 +0,0 @@ -[[facets]] -category = "genre" -value = "tutorial" diff --git a/source/archive-reference-files/quick-start/next-steps.txt b/source/archive-reference-files/quick-start/next-steps.txt deleted file mode 100644 index 55d656e6c..000000000 --- a/source/archive-reference-files/quick-start/next-steps.txt +++ /dev/null @@ -1,22 +0,0 @@ -.. _node-quick-start-next-steps: - -========== -Next Steps -========== - -.. meta:: - :description: Explore further resources to enhance your understanding of the MongoDB Node.js Driver, including CRUD operations and usage examples. - -Congratulations on completing the quick start tutorial! - -In this tutorial, you created a Node.js application that -connects to a MongoDB deployment hosted on MongoDB Atlas -and retrieves a document that matches a query. - -Learn more about the {+driver-long+} from the following resources: - -- Discover how to perform read and write operations in the - :ref:`CRUD Operations ` section. - -- See examples of frequently-used operations in the - :ref:`Usage Examples ` section. diff --git a/source/connect/connection-options/connection-pools.txt b/source/connect/connection-options/connection-pools.txt index 2050239bf..f70abd878 100644 --- a/source/connect/connection-options/connection-pools.txt +++ b/source/connect/connection-options/connection-pools.txt @@ -1,8 +1,8 @@ .. _node-connection-pools: -================ -Connection Pools -================ +======================================== +Manage Connections with Connection Pools +======================================== .. facet:: :name: genre @@ -27,4 +27,253 @@ gets 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 new connections -are created by {+driver-short+}. \ No newline at end of file +are created by {+driver-short+}. + +.. _node-faq-connection-pool: + +Configure Connection Pools +-------------------------- + +Every ``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 to support concurrent requests to +MongoDB in your application. + +You can specify the following connection pool settings in your ``MongoClient`` +instance: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Setting + - Description + + * - ``maxPoolSize`` + - | The maximum number of concurrent connections that the pool maintains. + If the number of in-use connections to a server reaches the specified + value, the next request to that server waits until a connection becomes + available. + | + | **Default**: ``100`` + + * - ``maxConnecting`` + - | The maximum number of connections that each pool can establish + concurrently. + + * - ``minPoolSize`` + - | The minimum number of concurrent connections that the pool maintains. + | + | **Default**: ``0`` + + * - ``maxIdleTimeMS`` + - | The maximum number of milliseconds that a connection can remain idle in + the pool. + | + | **Default**: ``0`` (no limit) + + * - ``waitQueueTimeoutMS`` + - | The maximum number of milliseconds that a request can wait for a socket + to become available. + | + | **Default**: ``0`` (no limit) + + +.. _node-connection-pool-max-pool-size: + +maxPoolSize +~~~~~~~~~~~ + +In addition to the sockets needed to support your application's requests, each +``MongoClient`` instance opens up to two connections per server in your +MongoDB topology for monitoring 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 (default) node, then 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, those +connection pools grow and there can be ``306`` total connections including the +open monitoring sockets. + +To support high numbers of concurrent MongoDB requests +within one process, you can increase ``maxPoolSize``. + +The following code creates a ``MongoClient`` instance with a maximum connection +pool size of ``200`` by specifying the ``maxPoolSize`` option in the +``options`` object: + +.. code-block:: javascript + + const { MongoClient } = require('mongodb'); + + const uri = ''; + const client = new MongoClient(uri, { + maxPoolSize: 200 + }); + +.. _node-connection-pool-max-connecting: + +maxConnecting +~~~~~~~~~~~~~ + +Connection pools rate-limit connection establishment. The ``maxConnecting`` +option determines the number of connections that the pool can create in parallel +at any time. For example, if the value of ``maxConnecting`` is ``2``, the third +request that attempts to concurrently check out a connection succeeds only when +one the following cases occurs: + +- The connection pool finishes creating a connection and there are fewer + than ``maxPoolSize`` connections in the pool. +- An existing connection is checked back into the pool. + +The following code creates a ``MongoClient`` instance with a maximum number of +``2`` connections to be established concurrently per pool by specifying the +``maxConnecting`` option in the ``options`` object: + +.. code-block:: javascript + + const { MongoClient } = require('mongodb'); + + const uri = ''; + const client = new MongoClient(uri, { + maxConnecting: 2 + }); + +.. _node-connection-pool-min-pool-size: + +minPoolSize +~~~~~~~~~~~ + +You can set the minimum number of connections to each server with the +``minPoolSize`` option. The driver ensures that there are always at least the +number of connections set by the ``minPoolSize`` option in the connection pool. +If sockets are closed, causing the total number of sockets (both in use and +idle) to drop below the minimum, more sockets are opened until the minimum is +reached. + +The following code creates a ``MongoClient`` instance with a minimum connnection +pool size of ``10`` by specifying the ``minPoolSize`` option in the ``options`` +object: + +.. code-block:: javascript + + const { MongoClient } = require('mongodb'); + + const uri = ''; + const client = new MongoClient(uri, { + minPoolSize: 10 + }); + +.. _node-connection-pool-max-idle-time: + +maxIdleTimeMS +~~~~~~~~~~~~~ + +You can set the maximum number of milliseconds that a connection can +remain idle in the pool by setting the ``maxIdleTimeMS`` option. +Once a connection has been idle for ``maxIdleTimeMS``, the connection +pool removes and replaces it. This option defaults to ``0`` (no limit). + +The following code creates a ``MongoClient`` instance with a maximum idle time +of ``10000`` milliseconds (10 seconds) by specifying the ``maxIdleTimeMS`` +setting in the ``options`` object: + +.. code-block:: javascript + + const { MongoClient } = require('mongodb'); + + const uri = ''; + const client = new MongoClient(uri, { + maxIdleTimeMS: 10000 + }); + +.. _node-connection-pool-wait-queue-timeout: + +waitQueueTimeoutMS +~~~~~~~~~~~~~~~~~~ + +``MongoClient`` supports multiple concurrent requests. For each process, +create a client and reuse it for all operations in a process. This +practice is more efficient than creating a client for each request. + +The driver does not limit the number of requests that +can wait for sockets to become available, and it is the application's +responsibility to limit the size of its pool to bound queuing +during a load spike. Requests wait for the amount of time specified in +the ``waitQueueTimeoutMS`` option, which defaults to ``0`` (no limit). + +A request that waits more than the length of time defined by +``waitQueueTimeoutMS`` for a socket raises a connection error. Use this +option if it is more important to bound the duration of operations +during a load spike than it is to complete every operation. + +The following code creates a ``MongoClient`` instance with a maximum wait queue +timeout of ``10000`` milliseconds (10 seconds) by declaring it in the +``options`` object: + +.. code-block:: javascript + + const { MongoClient } = require('mongodb'); + + const uri = ''; + const client = new MongoClient(uri, { + waitQueueTimeoutMS: 10000 + }); + +Closing Connections +-------------------- + +When any request calls ``MongoClient.close()``, the {+driver-short+} performs +the following actions: + +- Closes all idle sockets in the connection pool +- Closes all sockets that are in use as they are returned to the pool +- Closes all sockets that are in use only when the associated operations + complete + +Calling ``MongoClient.close()`` closes only inactive sockets and does not +directly terminate any ongoing operations. + +.. note:: + + The ``MongoClient.close()`` method does close existing sessions and + transactions, which might indirectly affect the behavior of ongoing + operations and open cursors. + +Avoid Socket Timeouts +--------------------- + +Having a large connection pool does not always reduce reconnection +requests. Consider the following example scenario: + +- An application has a connection pool size of 5 sockets and has the + ``socketTimeoutMS`` option set to 5000 milliseconds. +- Operations occur, on average, every 3000 milliseconds, and reconnection + requests are frequent. +- Each socket times out after 5000 milliseconds, which means that all sockets + must do something during those 5000 milliseconds to avoid closing. + +In this scenario, each socket times out after 5000 milliseconds, requiring +activity within this timeout period to avoid closure. However, one message every +3000 milliseconds isn't enough to keep all sockets active, causing several of +them to time out. + +To avoid excessive socket timeouts, reduce the number of connections that the +driver can maintain in the connection pool by specifying the ``maxPoolSize`` +option. To learn how to set the ``maxPoolSize`` option, see the +:ref:`node-connection-pool-max-pool-size` section. + +API Documentation +----------------- + +For more information about creating a ``MongoClient`` object with the +{+driver-short+} and specifying options, see the following API documentation: + +- `MongoClient <{+api+}/classes/MongoClient.html>`__ +- `MongoClientOptions <{+api+}/interfaces/MongoClientOptions.html>`__ +- `maxPoolSize <{+api+}/interfaces/MongoClientOptions.html#maxPoolSize>`__ +- `maxConnecting <{+api+}/interfaces/MongoClientOptions.html#maxConnecting>`__ +- `minPoolSize <{+api+}/interfaces/MongoClientOptions.html#minPoolSize>`__ +- `maxIdleTimeMS <{+api+}/interfaces/MongoClientOptions.html#maxIdleTimeMS>`__ +- `waitQueueTimeoutMS <{+api+}/interfaces/MongoClientOptions.html#waitQueueTimeoutMS>`__ diff --git a/source/connect/connection-targets.txt b/source/connect/connection-targets.txt index df72aba8a..20e3d09e2 100644 --- a/source/connect/connection-targets.txt +++ b/source/connect/connection-targets.txt @@ -15,4 +15,97 @@ Choose a Connection Target :local: :backlinks: none :depth: 2 - :class: singlecol \ No newline at end of file + :class: singlecol + +.. _node-other-ways-to-connect: + +Overview +-------- + +In this guide, you can learn how to use a connection string and a ``MongoClient`` +object to connect to different types of MongoDB deployments. + +.. tip:: + + To learn more about how to retrieve your connection string, see + the :atlas:`Connect via Drivers ` guide in + the Atlas documentation. + +Atlas +----- + +To connect to a MongoDB deployment on Atlas, include the following elements +in your connection string: + +- URL of your Atlas cluster +- MongoDB username +- MongoDB password + +Then, pass your connection string to the ``MongoClient`` constructor. + +When you connect to Atlas, we recommend using the {+stable-api+} client option to avoid +breaking changes when Atlas upgrades to a new version of {+mdb-server+}. +To learn more about the {+stable-api+} feature, see the :ref:`` +guide. + +The following code shows how to use the {+driver-short+} to connect to an Atlas cluster. The +code also uses the ``server_api`` field to specify a {+stable-api+} version. + +.. literalinclude:: /includes/connect/connection-targets.js + :language: javascript + :start-after: start-connection-target-atlas + :end-before: end-connection-target-atlas + :dedent: + +Local Deployments +----------------- + +To connect to a local standalone MongoDB deployment, specify the host of the +server. Optionally, specify the port of the server. If no port is specified, +the default port is ``27017``. + +You can specify the host and port to connect to by using a +connection string, as shown in the following code: + +.. literalinclude:: /includes/connect/connection-targets.js + :language: javascript + :start-after: start-local-connection-uri + :end-before: end-local-connection-uri + :dedent: + +You can also specify your host as ``localhost``. The following code example +connects to ``localhost`` on the specified port: + +.. literalinclude:: /includes/connect/connection-targets.js + :language: javascript + :start-after: start-localhost + :end-before: end-localhost + :dedent: + +Replica Sets +------------ + +To connect to a replica set, we recommend that you specify all nodes that are +part of the replica set. If one or more nodes becomes unavailable, +specifying all nodes allows the driver to still connect to the replica set +if one node is available. + +However, it is sufficient to pass the address of any one node in the replica set +to the driver. The node does not need to be the primary, and it may be a hidden node. +The driver will then automatically discover the remaining nodes. + +The following example shows how to connect to the replica set by using a connection +string and how to verify the replica set name on connection by using the +``replicaSet`` connection string option: + +.. literalinclude:: /includes/connect/connection-targets.js + :language: javascript + :start-after: start-replica-set-option + :end-before: end-replica-set-option + :dedent: + +API Documentation +----------------- + +To learn more about creating a ``MongoClient`` object with the {+driver-short+}, +see the API documentation for `MongoClient <{+api+}/classes/MongoClient.html>`__ .