diff --git a/config/redirects b/config/redirects index 5119e2f69..061d85f10 100644 --- a/config/redirects +++ b/config/redirects @@ -10,6 +10,7 @@ raw: ${prefix}/stable -> ${base}/current/ [*-master]: ${prefix}/${version}/fundamentals/versioned-api/ -> ${base}/${version}/fundamentals/stable-api/ [*-master]: ${prefix}/${version}/fundamentals/connection/lambda/ -> ${base}/${version}/fundamentals/connection/ [*-master]: ${prefix}/${version}/fundamentals/csfle -> ${base}/${version}/fundamentals/encrypt-fields/ +[*-master]: ${prefix}/${version}/faq/ -> ${base}/${version}/ [*-v5.0]: ${prefix}/${version}/quick-start/connect-to-mongodb/ -> ${base}/${version}/quick-start/ [*-v5.0]: ${prefix}/${version}/quick-start/create-a-connection-string/ -> ${base}/${version}/quick-start/ @@ -23,4 +24,84 @@ 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}/ + +# Comprehensive Coverage Redirects + +[v6.16-master]: ${prefix}/${version}/quick-start/download-and-install/ -> ${base}/${version}/get-started/ +[v6.16-master]: ${prefix}/${version}/quick-start/create-a-deployment/ -> ${base}/${version}/get-started/ +[v6.16-master]: ${prefix}/${version}/quick-start/create-a-connection-string/ -> ${base}/${version}/get-started/ +[v6.16-master]: ${prefix}/${version}/quick-start/connect-to-mongodb/ -> ${base}/${version}/get-started/ +[v6.16-master]: ${prefix}/${version}/quick-start/next-steps/ -> ${base}/${version}/get-started/ +[v6.16-master]: ${prefix}/${version}/fundamentals/connection/ -> ${base}/${version}/connect/ +[v6.16-master]: ${prefix}/${version}/fundamentals/connection/connect/ -> ${base}/${version}/connect/mongoclient/ +[v6.16-master]: ${prefix}/${version}/fundamentals/connection/connection-options/ -> ${base}/${version}/connect/connection-options/ +[v6.16-master]: ${prefix}/${version}/connection-troubleshooting/ -> ${base}/${version}/connect/connection-troubleshooting/ +[v6.16-master]: ${prefix}/${version}/fundamentals/connection/network-compression/ -> ${base}/${version}/connect/connection-options/network-compression/ +[v6.16-master]: ${prefix}/${version}/fundamentals/connection/csot/ -> ${base}/${version}/connect/connection-options/csot/ +[v6.16-master]: ${prefix}/${version}/fundamentals/crud/write-operations/bulk/ -> ${base}/${version}/crud/bulk-write/ +[v6.16-master]: ${prefix}/${version}/fundamentals/crud/write-operations/insert/ -> ${base}/${version}/crud/insert/ +[v6.16-master]: ${prefix}/${version}/fundamentals/crud/write-operations/upsert/ -> ${base}/${version}/crud/update/ +[v6.16-master]: ${prefix}/${version}/fundamentals/crud/write-operations/delete/ -> ${base}/${version}/crud/delete/ +[v6.16-master]: ${prefix}/${version}/fundamentals/crud/read-operations/ -> ${base}/${version}/crud/query/ +[v6.16-master]: ${prefix}/${version}/fundamentals/crud/query-document/ -> ${base}/${version}/crud/query/query-document/ +[v6.16-master]: ${prefix}/${version}/fundamentals/crud/compound-operations/ -> ${base}/${version}/crud/compound-operations/ +[v6.16-master]: ${prefix}/${version}/fundamentals/crud/read-write-pref/ -> ${base}/${version}/crud/configure/ +[v6.16-master]: ${prefix}/${version}/fundamentals/transactions/ -> ${base}/${version}/crud/transactions/ +[v6.16-master]: ${prefix}/${version}/fundamentals/gridfs/ -> ${base}/${version}/crud/gridfs/ +[v6.16-master]: ${prefix}/${version}/fundamentals/crud/read-operations/retrieve/ -> ${base}/${version}/crud/query/retrieve/ +[v6.16-master]: ${prefix}/${version}/fundamentals/crud/read-operations/project/ -> ${base}/${version}/crud/query/project/ +[v6.16-master]: ${prefix}/${version}/fundamentals/crud/read-operations/distinct/ -> ${base}/${version}/crud/query/distinct/ +[v6.16-master]: ${prefix}/${version}/fundamentals/crud/read-operations/cursor/ -> ${base}/${version}/crud/query/cursor/ +[v6.16-master]: ${prefix}/${version}/fundamentals/crud/read-operations/geo/ -> ${base}/${version}/crud/query/geo/ +[v6.16-master]: ${prefix}/${version}/fundamentals/crud/time-series/ -> ${base}/${version}/data-formats/time-series/ +[v6.16-master]: ${prefix}/${version}/fundamentals/bson/ -> ${base}/${version}/data-formats/bson/ +[v6.16-master]: ${prefix}/${version}/fundamentals/indexes/ -> ${base}/${version}/indexes/ +[v6.16-master]: ${prefix}/${version}/fundamentals/run-command/ -> ${base}/${version}/run-command/ +[v6.16-master]: ${prefix}/${version}/fundamentals/monitoring/ -> ${base}/${version}/monitoring-and-logging/monitoring/ +[v6.16-master]: ${prefix}/${version}/fundamentals/logging/ -> ${base}/${version}/monitoring-and-logging/logging/ +[v6.16-master]: ${prefix}/${version}/usage-examples/changeStream -> ${base}/monitoring-and-logging/change-streams/ +[v6.16-master]: ${prefix}/${version}/fundamentals/aggregation/ -> ${base}/${version}/aggregation/ +[v6.16-master]: ${prefix}/${version}/aggregation-tutorials/ -> ${base}/aggregation/ +[v6.16-master]: ${prefix}/${version}/aggregation-tutorials/filtered-subset/ -> ${base}/aggregation/filtered-subset/ +[v6.16-master]: ${prefix}/${version}/aggregation-tutorials/group-total/ -> ${base}/aggregation/group-total/ +[v6.16-master]: ${prefix}/${version}/aggregation-tutorials/multi-field-join/ -> ${base}/aggregation/multi-field-join/ +[v6.16-master]: ${prefix}/${version}/aggregation-tutorials/one-to-one-join/ -> ${base}/aggregation/one-to-one-join/ +[v6.16-master]: ${prefix}/${version}/aggregation-tutorials/unpack-arrays/ -> ${base}/aggregation/unpack-arrays/ +[v6.16-master]: ${prefix}/${version}/fundamentals/authentication -> ${base}/security/authentication/ +[v6.16-master]: ${prefix}/${version}/fundamentals/authentication/mechanisms/ -> ${base}/security/authentication/mechanisms/ +[v6.16-master]: ${prefix}/${version}/fundamentals/authentication/enterprise-mechanisms/ -> ${base}/security/authentication/enterprise-mechanisms/ +[v6.16-master]: ${prefix}/${version}/fundamentals/encrypt-fields/ -> ${base}/security/encrypt-fields/ +[v6.16-master]: ${prefix}/${version}/fundamentals/connection/tls/ -> ${base}/security/tls/ +[v6.16-master]: ${prefix}/${version}/fundamentals/connection/socks/ -> ${base}/security/socks/ +[v6.16-master]: ${prefix}/${version}/fundamentals/typescript/ -> ${base}/typescript/ +[v6.16-master]: ${prefix}/${version}/whats-new/ -> ${base}/reference/release-notes/ +[v6.16-master]: ${prefix}/${version}/compatibility/ -> ${base}/reference/compatibility/ +[v6.16-master]: ${prefix}/${version}/upgrade/ -> ${base}/reference/upgrade/ +[v6.16-master]: ${prefix}/${version}/quick-reference/ -> ${base}/reference/quick-reference/ +[v6.16-master]: ${prefix}/${version}/fundamentals/collations/ -> ${base}/crud/configure/ +[v6.16-master]: ${prefix}/${version}/fundamentals/crud/read-operations/text/ -> ${base}/crud/query/text/ +[v6.16-master]: ${prefix}/${version}/fundamentals/crud/write-operations/modify/ -> ${base}/crud/update/modify/ +[v6.16-master]: ${prefix}/${version}/fundamentals/crud/write-operations/embedded-arrays/ -> ${base}/crud/update/embedded-arrays/ +[v6.16-master]: ${prefix}/${version}/fundamentals/crud/write-operations/pkFactory/ -> ${base}/crud/pkFactory/ +[v6.16-master]: ${prefix}/${version}/security/authentication/enterprise-mechanisms/ -> ${base}/security/authentication +[v6.16-master]: ${prefix}/${version}/fundamentals/promises/ -> ${base}/promises/ + +# Usage Example Redirects + +[v6.16-master]: ${prefix}/${version}/usage-examples/findOne/ -> ${base}/crud/query/retrieve/ +[v6.16-master]: ${prefix}/${version}/usage-examples/find/ -> ${base}/crud/query/retrieve/ +[v6.16-master]: ${prefix}/${version}/usage-examples/insertOne/ -> ${base}/crud/insert/ +[v6.16-master]: ${prefix}/${version}/usage-examples/insertMany/ -> ${base}/crud/insert/ +[v6.16-master]: ${prefix}/${version}/usage-examples/updateOne/ -> ${base}/crud/update/modify/ +[v6.16-master]: ${prefix}/${version}/usage-examples/updateMany/ -> ${base}/crud/update/modify/ +[v6.16-master]: ${prefix}/${version}/usage-examples/replaceOne/ -> ${base}/crud/update/replace/ +[v6.16-master]: ${prefix}/${version}/usage-examples/deleteOne/ -> ${base}/crud/delete/ +[v6.16-master]: ${prefix}/${version}/usage-examples/deleteMany/ -> ${base}/crud/delete/ +[v6.16-master]: ${prefix}/${version}/usage-examples/count/ -> ${base}/crud/query/count/ +[v6.16-master]: ${prefix}/${version}/usage-examples/distinct/ -> ${base}/crud/query/distinct/ +[v6.16-master]: ${prefix}/${version}/usage-examples/command/ -> ${base}/run-command/ +[v6.16-master]: ${prefix}/${version}/usage-examples/bulkWrite/ -> ${base}/bulk-write/ +[v6.16-master]: ${prefix}/${version}/usage-examples/transactions/ -> ${base}/crud/transactions/ +[v6.16-master]: ${prefix}/${version}/usage-examples/transaction-conv/ -> ${base}/crud/transactions/transaction-conv/ +[v6.16-master]: ${prefix}/${version}/usage-examples/transaction-core/ -> ${base}/crud/transactions/transaction-core/ \ No newline at end of file diff --git a/snooty.toml b/snooty.toml index 57178bd89..ec8980a92 100644 --- a/snooty.toml +++ b/snooty.toml @@ -7,14 +7,20 @@ 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", + "/crud/transactions", + "/monitoring-and-logging" ] sharedinclude_root = "https://raw.githubusercontent.com/10gen/docs-shared/main/" @@ -26,3 +32,5 @@ driver-short = "Node.js driver" mdb-server = "MongoDB Server" min-node-version = "v16.20.1" stable-api = "Stable API" +vector-search = "Atlas Vector Search" +language = "JavaScript" \ No newline at end of file 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 55% rename from source/fundamentals/aggregation.txt rename to source/aggregation.txt index a158b589a..c4f2504e4 100644 --- a/source/fundamentals/aggregation.txt +++ b/source/aggregation.txt @@ -5,8 +5,12 @@ Aggregation =========== +.. facet:: + :name: genre + :values: reference + .. meta:: - :description: Learn to use aggregation operations in the MongoDB Node.js Driver to create pipelines for data transformation and summarization. + :keywords: node.js, code example, runnable app .. contents:: On this page :local: @@ -14,6 +18,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 +113,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 +146,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/atlas-search.txt b/source/atlas-search.txt new file mode 100644 index 000000000..bef911d49 --- /dev/null +++ b/source/atlas-search.txt @@ -0,0 +1,113 @@ +.. _node-atlas-search: + +========================= +Run an Atlas Search Query +========================= + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: full text, text analyzer, meta, pipeline, scoring, Lucene + :description: Learn about how to use Atlas Search in the {+driver-long+}. + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +In this guide, you can learn how to use the {+driver-short+} to +run :atlas:`Atlas Search ` queries on a collection. +Atlas Search enables you to perform full-text searches on collections +hosted on MongoDB Atlas. Atlas Search indexes specify the behavior of the +search and which fields to index. + +Sample Data +~~~~~~~~~~~ + +The example in this guide uses the ``movies`` collection in the ``sample_mflix`` +database from the :atlas:`Atlas sample datasets `. To learn how to +create a free MongoDB Atlas cluster and load the sample datasets, see the +:atlas:`Get Started with Atlas ` guide. + +Run an Atlas Search Query +------------------------- + +This section shows how to create an aggregation pipeline to run an +Atlas Search query on a collection. In your array of pipeline stages, +add the ``$search`` stage to specify the search criteria. Then, call +the ``aggregate()`` method and pass your pipeline array as a parameter. + +.. tip:: + + To learn more about aggregation operations, see the :ref:`node-aggregation` + guide. + +Before running an Atlas Search query, you must create an Atlas Search index +on your collection. To learn how to programmatically create an Atlas Search +index, see the :ref:`node-indexes-search` section of the Indexes guide. + +Atlas Search Example +~~~~~~~~~~~~~~~~~~~~ + +This example runs an Atlas Search query by performing the +following actions: + +- Creates a ``$search`` stage that instructs the driver + to query for documents in which the ``title`` field contains + the word ``"Alabama"`` + +- Creates a ``$project`` stage that instructs the driver to + include the ``title`` field in the query results + +- Passes the pipeline stages to the ``aggregate()`` method and + prints the results + +.. io-code-block:: + :copyable: + + .. input:: /includes/atlas-search.js + :start-after: begin-atlas-search + :end-before: end-atlas-search + :language: java + :dedent: + + .. output:: + :language: console + :visible: false + + { + _id: new ObjectId('...'), + title: 'Alabama Moon' + } + { + _id: new ObjectId('...'), + title: 'Crazy in Alabama' + } + { + _id: new ObjectId('...'), + title: 'Sweet Home Alabama' + } + +.. tip:: Node.js Driver Atlas Search Examples + + To view more examples that use the {+driver-short+} to perform Atlas + Search queries, see :atlas:`Atlas Search Tutorials ` + in the Atlas documentation. + +Additional Information +---------------------- + +To learn more about Atlas Search, see :atlas:`Atlas Search ` +in the Atlas documentation. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about the ``aggregate()`` method, see the +`API documentation <{+api+}/classes/Collection.html#aggregate>`__. \ No newline at end of file diff --git a/source/atlas-vector-search.txt b/source/atlas-vector-search.txt new file mode 100644 index 000000000..1d3ede7d9 --- /dev/null +++ b/source/atlas-vector-search.txt @@ -0,0 +1,177 @@ +.. _node-atlas-vector-search: + +================================ +Run an Atlas Vector Search Query +================================ + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example, semantic, nearest + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +In this guide, you can learn how to use the Atlas Vector Search feature +in the {+driver-short+}. + +You can use {+vector-search+} to perform a vector search on your data stored in +Atlas. Vector search allows you to query your data based on semantic meaning +rather than just keyword matches, which helps you retrieve more relevant search +results. It enables your AI-powered applications to support use cases such as +semantic search, hybrid search, and generative search, including +Retrieval-Augmented Generation (RAG). + +To learn more about {+vector-search+}, see the :atlas:`{+vector-search+} +` guides in the MongoDB Atlas +documentation. + +.. important:: Feature Compatibility + + To learn what versions of MongoDB Atlas support this feature, see + :atlas:`Limitations ` + in the MongoDB Atlas documentation. + +Perform a Vector Search +----------------------- + +To use this feature, you must create a vector search index and index your +vector embeddings. To learn about how to programmatically create a +vector search index, see the :ref:`` section in the +Indexes guide. To learn more about vector embeddings, see +:atlas:`How to Create Vector Embeddings +` in the Atlas documentation. + +After you create a vector search index on your vector embeddings, you +can reference this index in your pipeline stage, as shown in the +following example. + +Sample Data +~~~~~~~~~~~ + +The example on this page shows how to build an aggregation pipeline that uses the +``$vectorSearch`` stage to perform a vector search on the +``sample_mflix.embedded_movies`` collection in the :atlas:`Atlas sample datasets +`. + +To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the +:atlas:`Get Started with Atlas ` guide. + +Vector Search Example +~~~~~~~~~~~~~~~~~~~~~ + +You can perform a vector search query by using the ``$vectorSearch`` stage +in an :ref:`aggregation pipeline `. To perform a vector +search on a collection, you must first have a collection with a field that contains +vector embeddings and a vector search index that covers that field. + +In the following example, the aggregation pipeline searches the ``plot`` field of each +document in the collection for text semantically related to the term "time travel". The +``queryVector`` field in the ``$vectorSearch`` pipeline is the vector representation of +your query. + +.. io-code-block:: + :copyable: true + + .. input:: /includes/aggregation/atlas-vector-search-example.js + :language: javascript + :dedent: + + .. output:: + :language: javascript + :visible: false + + { + plot: 'A reporter, learning of time travelers visiting 20th century disasters, tries to change the history they know by averting upcoming disasters.', + title: 'Thrill Seekers', + score: 0.9259490966796875 + } + { + plot: 'At the age of 21, Tim discovers he can travel in time and change what happens and has happened in his own life. His decision to make his world a better place by getting a girlfriend turns out not to be as easy as you might think.', + title: 'About Time', + score: 0.9253997802734375 + } + { + plot: 'An officer for a security agency that regulates time travel, must fend for his life against a shady politician who has a tie to his past.', + title: 'Timecop', + score: 0.922332763671875 + } + { + plot: "After using his mother's newly built time machine, Dolf gets stuck + involuntary in the year 1212. He ends up in a children's crusade where he confronts + his new friends with modern techniques...", + title: 'Crusade in Jeans', + score: 0.92205810546875 + } + { + plot: 'Hoping to alter the events of the past, a 19th century inventor instead travels 800,000 years into the future, where he finds humankind divided into two warring races.', + title: 'The Time Machine', + score: 0.921875 + } + { + plot: 'A time-travel experiment in which a robot probe is sent from the year 2073 to the year 1973 goes terribly wrong thrusting one of the project scientists, a man named Nicholas Sinclair into a...', + title: 'A.P.E.X.', + score: 0.9202728271484375 + } + { + plot: "Agent J travels in time to M.I.B.'s early days in 1969 to stop an alien from assassinating his friend Agent K and changing history.", + title: 'Men in Black 3', + score: 0.9198150634765625 + } + { + plot: 'Bound by a shared destiny, a teen bursting with scientific curiosity and a former boy-genius inventor embark on a mission to unearth the secrets of a place somewhere in time and space that exists in their collective memory.', + title: 'Tomorrowland', + score: 0.91961669921875 + } + { + plot: 'A romantic drama about a Chicago librarian with a gene that causes him to involuntarily time travel, and the complications it creates for his marriage.', + title: "The Time Traveler's Wife", + score: 0.9174346923828125 + } + { + plot: 'With the help of his uncle, a man travels to the future to try and bring his girlfriend back to life.', + title: 'Love Story 2050', + score: 0.9165191650390625 + } + +This query uses the ``$vectorSearch`` stage to: + +- Perform an Approximate Nearest Neighbor (ANN) vector search + +- Search for the specified term in the ``plot_embedding`` field + +- Set the number of nearest neighbors used in the search to 150 by using the + ``numCandidates`` option + +- Return a maximum of 10 documents from the query using the ``limit`` option + +It uses the ``$project`` stage to: + +- Only include the movie ``plot`` and ``title`` fields in the results + +- Add a ``score`` field to show the relevance of each result to the search term + +Additional Information +---------------------- + +To see more Atlas Vector Search tutorials for the {+driver-short+}, see the :atlas:`Atlas +Vector Search tutorials ` in the Atlas documentation. + +To learn more about the syntax of the ``$vectorSearch`` pipeline stage, +see the Syntax and Fields sections of the +:atlas:`Create and Run Queries ` +guide in the Atlas Vector Search section of the Atlas documentation. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about the ``aggregate()`` method, see `aggregate() +<{+api+}/classes/Collection.html#aggregate>`__ in the API documentation. diff --git a/source/code-snippets/authentication/aws-env-variable.js b/source/code-snippets/authentication/aws-env-variable.js index 3533a04fc..f8e93fd31 100644 --- a/source/code-snippets/authentication/aws-env-variable.js +++ b/source/code-snippets/authentication/aws-env-variable.js @@ -1,7 +1,7 @@ const { MongoClient } = require("mongodb"); // Remember to specify your AWS credentials in environment variables. -const clusterUrl = ""; +const clusterUrl = ""; const authMechanism = "MONGODB-AWS"; let uri = diff --git a/source/code-snippets/authentication/aws.js b/source/code-snippets/authentication/aws.js index da158e5b4..2033c009d 100644 --- a/source/code-snippets/authentication/aws.js +++ b/source/code-snippets/authentication/aws.js @@ -3,7 +3,7 @@ const { MongoClient } = require("mongodb"); // Replace the following with values for your environment. const accessKeyId = encodeURIComponent(""); const secretAccessKey = encodeURIComponent(""); -const clusterUrl = ""; +const clusterUrl = ""; const authMechanism = "MONGODB-AWS"; diff --git a/source/code-snippets/authentication/cr.js b/source/code-snippets/authentication/cr.js index 0c8605c13..109a871f6 100644 --- a/source/code-snippets/authentication/cr.js +++ b/source/code-snippets/authentication/cr.js @@ -3,7 +3,7 @@ const { MongoClient } = require("mongodb"); // Replace the following with values for your environment. const username = encodeURIComponent(""); const password = encodeURIComponent(""); -const clusterUrl = ""; +const clusterUrl = ""; // Replace the following with your MongoDB deployment's connection string. const uri = diff --git a/source/code-snippets/authentication/default.js b/source/code-snippets/authentication/default.js index b8c60c882..30f18a2f5 100644 --- a/source/code-snippets/authentication/default.js +++ b/source/code-snippets/authentication/default.js @@ -3,7 +3,7 @@ const { MongoClient } = require("mongodb"); // Replace the following with values for your environment. const username = encodeURIComponent(""); const password = encodeURIComponent(""); -const clusterUrl = ""; +const clusterUrl = ""; const authMechanism = "DEFAULT"; diff --git a/source/code-snippets/authentication/sha1.js b/source/code-snippets/authentication/sha1.js index 32dc9fd33..7b932bc79 100644 --- a/source/code-snippets/authentication/sha1.js +++ b/source/code-snippets/authentication/sha1.js @@ -3,7 +3,7 @@ const { MongoClient } = require("mongodb"); // Replace the following with values for your environment. const username = encodeURIComponent(""); const password = encodeURIComponent(""); -const clusterUrl = ""; +const clusterUrl = ""; const authMechanism = "SCRAM-SHA-1"; diff --git a/source/code-snippets/authentication/sha256.js b/source/code-snippets/authentication/sha256.js index 86dfbb499..e44ea9046 100644 --- a/source/code-snippets/authentication/sha256.js +++ b/source/code-snippets/authentication/sha256.js @@ -3,7 +3,7 @@ const { MongoClient } = require("mongodb"); // Replace the following with values for your environment. const username = encodeURIComponent(""); const password = encodeURIComponent(""); -const clusterUrl = ""; +const clusterUrl = ""; const authMechanism = "SCRAM-SHA-256"; diff --git a/source/code-snippets/authentication/x509.js b/source/code-snippets/authentication/x509.js index fffe07529..224a865b5 100644 --- a/source/code-snippets/authentication/x509.js +++ b/source/code-snippets/authentication/x509.js @@ -1,8 +1,8 @@ const { MongoClient } = require("mongodb"); // Replace the following with values for your environment. -const clusterUrl = ""; -const clientPEMFile = encodeURIComponent(""); +const clusterUrl = ""; +const clientPEMFile = encodeURIComponent(""); const authMechanism = "MONGODB-X509"; diff --git a/source/code-snippets/indexes/searchIndexes.js b/source/code-snippets/indexes/searchIndexes.js index d0ac72398..8eeff5770 100644 --- a/source/code-snippets/indexes/searchIndexes.js +++ b/source/code-snippets/indexes/searchIndexes.js @@ -17,7 +17,7 @@ async function run() { const collection = database.collection(""); // start createSearchIndex example - // Create a search index + // Creates an Atlas Search index const index1 = { name: "search1", definition: { @@ -30,7 +30,7 @@ async function run() { // end createSearchIndex example // start vectorSearchIdx example - // Create a Vector Search index + // Creates an Atlas Vector Search index const vectorSearchIdx = { name: "vsidx1", type: "vectorSearch", @@ -48,7 +48,7 @@ async function run() { // end vectorSearchIdx example // start listSearchIndexes example - // List search indexes + // Lists search indexes const result = await collection.listSearchIndexes().toArray(); console.log("Existing search indexes:\n"); for (const doc in result) { @@ -57,7 +57,7 @@ async function run() { // end listSearchIndexes example // start updateSearchIndex example - // Update a search index + // Updates a search index const index2 = { "mappings": { "dynamic": true, @@ -72,7 +72,7 @@ async function run() { // end updateSearchIndex example // start dropSearchIndex example - // Dropping (deleting) a search index + // Drops (deletes) a search index await collection.dropSearchIndex("search1"); // end dropSearchIndex example } finally { diff --git a/source/code-snippets/monitoring/apm-subscribe.js b/source/code-snippets/monitoring/apm-subscribe.js index fb53b757c..524c01788 100644 --- a/source/code-snippets/monitoring/apm-subscribe.js +++ b/source/code-snippets/monitoring/apm-subscribe.js @@ -10,16 +10,16 @@ const client = new MongoClient(uri, { monitorCommands:true }); // Replace with the name of the event you are subscribing to const eventName = ""; -// Subscribe to a specified event and print a message when the event is received +// Subscribes to a specified event and print a message when the event is received client.on(eventName, event => console.log(event)); async function run() { try { - // Establish and verify connection to the "admin" database + // Establishes and verifies connection to the "admin" database await client.db("admin").command({ ping: 1 }); console.log("Connected successfully"); } finally { - // Close the database connection on completion or error + // Closes the database connection on completion or error await client.close(); } } diff --git a/source/code-snippets/monitoring/cpm-subscribe.js b/source/code-snippets/monitoring/cpm-subscribe.js index 596af4178..ddcc6b564 100644 --- a/source/code-snippets/monitoring/cpm-subscribe.js +++ b/source/code-snippets/monitoring/cpm-subscribe.js @@ -9,14 +9,14 @@ const client = new MongoClient(uri); // Replace with the name of the event you are subscribing to const eventName = ""; -// Subscribe to the event +// Subscribes to the event client.on(eventName, (event) => console.log("\nreceived event:\n", event) ); async function run() { try { - // Establish and verify connection + // Establishes and verifies connection await client.db("admin").command({ ping: 1 }); console.log("\nConnected successfully!\n"); } finally { diff --git a/source/code-snippets/monitoring/sdam-subscribe.js b/source/code-snippets/monitoring/sdam-subscribe.js index 90db667f1..5f24919b4 100644 --- a/source/code-snippets/monitoring/sdam-subscribe.js +++ b/source/code-snippets/monitoring/sdam-subscribe.js @@ -10,18 +10,18 @@ const client = new MongoClient(uri); // Replace with the name of the event you are subscribing to const eventName = ""; -// Subscribe to a specified event and print a message when the event is received +// Subscribes to a specified event and prints a message when the event is received client.on(eventName, event => { console.log(`received ${eventName}: ${JSON.stringify(event, null, 2)}`); }); async function run() { try { - // Establish and verify connection to the database + // Establishes and verifies connection to the database await client.db("admin").command({ ping: 1 }); console.log("Connected successfully"); } finally { - // Close the database connection on completion or error + // Closes the database connection on completion or error await client.close(); } } diff --git a/source/code-snippets/usage-examples/find.js b/source/code-snippets/usage-examples/find.js index 0486e86d2..4a389c291 100644 --- a/source/code-snippets/usage-examples/find.js +++ b/source/code-snippets/usage-examples/find.js @@ -14,16 +14,11 @@ async function run() { // Query for movies that have a runtime less than 15 minutes const query = { runtime: { $lt: 15 } }; - - const options = { - // Sort returned documents in ascending order by title (A->Z) - sort: { title: 1 }, - // Include only the `title` and `imdb` fields in each returned document - projection: { _id: 0, title: 1, imdb: 1 }, - }; + const sortFields = { title: 1 }; + const projectFields = { _id: 0, title: 1, imdb: 1 }; // Execute query - const cursor = movies.find(query, options); + const cursor = movies.find(query).sort(sortFields).project(projectFields); // Print a message if no documents were found if ((await movies.countDocuments(query)) === 0) { diff --git a/source/code-snippets/usage-examples/find.ts b/source/code-snippets/usage-examples/find.ts index 123c1e2af..efab7839a 100644 --- a/source/code-snippets/usage-examples/find.ts +++ b/source/code-snippets/usage-examples/find.ts @@ -25,13 +25,10 @@ async function run() { const movies = database.collection("movies"); const query = { runtime: { $lt: 15 } }; - const cursor = movies.find( - query, - { - sort: { title: 1 }, - projection: { _id: 0, title: 1, imdb: 1 }, - } - ); + const sortFields = { title: 1 }; + const projectFields = { _id: 0, title: 1, imdb: 1 }; + + const cursor = movies.find(query).sort(sortFields).project(projectFields); if ((await movies.countDocuments(query)) === 0) { console.warn("No documents found!"); diff --git a/source/code-snippets/usage-examples/insertMany.js b/source/code-snippets/usage-examples/insertMany.js index 93725a522..e499740c0 100644 --- a/source/code-snippets/usage-examples/insertMany.js +++ b/source/code-snippets/usage-examples/insertMany.js @@ -9,21 +9,21 @@ async function run() { try { // Get the database and collection on which to run the operation - const database = client.db("insertDB"); - const foods = database.collection("foods"); + const database = client.db("sample_mflix"); + const movies = database.collection("movies"); // Create an array of documents to insert - const docs = [ - { name: "cake", healthy: false }, - { name: "lettuce", healthy: true }, - { name: "donut", healthy: false } + const moviesToInsert = [ + { title: "Arsenic and Old Lace", genres: ["Comedy", "Romance"], year: 1944, cast: ["Cary Grant", "Priscilla Lane", "Raymond Massey"] }, + { title: "Ball of Fire", genres: ["Comedy", "Romance"], year: 1941, cast: ["Gary Cooper", "Barbara Stanwyck", "Oskar Homolka"] }, + { title: "I Married a Witch", genres: ["Comedy", "Fantasy", "Romance"], year: 1942, cast: ["Veronica Lake", "Fredric March", "Susan Hayward"] }, ]; // Prevent additional documents from being inserted if one fails const options = { ordered: true }; // Execute insert operation - const result = await foods.insertMany(docs, options); + const result = await movies.insertMany(moviesToInsert, options); // Print result console.log(`${result.insertedCount} documents were inserted`); diff --git a/source/code-snippets/usage-examples/insertMany.ts b/source/code-snippets/usage-examples/insertMany.ts index 0b1eeb3ee..a9618a76a 100644 --- a/source/code-snippets/usage-examples/insertMany.ts +++ b/source/code-snippets/usage-examples/insertMany.ts @@ -5,24 +5,24 @@ const uri = ""; const client = new MongoClient(uri); -interface Food { - name: string; - healthy: boolean; +interface Movie { + title: string; + genres: string[]; + year: number; + cast: string[]; } async function run() { try { - const database = client.db("insertDB"); + const database = client.db("sample_mflix"); // Specifying a schema is optional, but it enables type hints on // finds and inserts - const foods = database.collection("foods"); + const movies = database.collection("movies"); - const result = await foods.insertMany( - [ - { name: "cake", healthy: false }, - { name: "lettuce", healthy: true }, - { name: "donut", healthy: false }, - ], + const result = await movies.insertMany( + { title: "Arsenic and Old Lace", genres: ["Comedy", "Romance"], year: 1944, cast: ["Cary Grant", "Priscilla Lane", "Raymond Massey"] }, + { title: "Ball of Fire", genres: ["Comedy", "Romance"], year: 1941, cast: ["Gary Cooper", "Barbara Stanwyck", "Oskar Homolka"] }, + { title: "I Married a Witch", genres: ["Comedy", "Fantasy", "Romance"], year: 1942, cast: ["Veronica Lake", "Fredric March", "Susan Hayward"] }, { ordered: true } ); console.log(`${result.insertedCount} documents were inserted`); diff --git a/source/code-snippets/usage-examples/insertOne.js b/source/code-snippets/usage-examples/insertOne.js index 1fe32e496..a8353e0fb 100644 --- a/source/code-snippets/usage-examples/insertOne.js +++ b/source/code-snippets/usage-examples/insertOne.js @@ -8,17 +8,19 @@ const client = new MongoClient(uri); async function run() { try { - // Connect to the "insertDB" database and access its "haiku" collection - const database = client.db("insertDB"); - const haiku = database.collection("haiku"); + // Connect to the "sample_mflix" database and access its "movies" collection + const database = client.db("sample_mflix"); + const movies = database.collection("movies"); // Create a document to insert const doc = { - title: "Record of a Shriveled Datum", - content: "No bytes, no problem. Just insert a document, in MongoDB", + title: "Charade", + genres: ["Comedy", "Romance", "Thriller"], + year: 1963, + cast: ["Cary Grant", "Audrey Hepburn", "Walter Matthau"], } - // Insert the defined document into the "haiku" collection - const result = await haiku.insertOne(doc); + // Insert the defined document into the "movies" collection + const result = await movies.insertOne(doc); // Print the ID of the inserted document console.log(`A document was inserted with the _id: ${result.insertedId}`); diff --git a/source/code-snippets/usage-examples/insertOne.ts b/source/code-snippets/usage-examples/insertOne.ts index 99a229bdf..3bdd1be4d 100644 --- a/source/code-snippets/usage-examples/insertOne.ts +++ b/source/code-snippets/usage-examples/insertOne.ts @@ -5,20 +5,24 @@ const uri = ""; const client = new MongoClient(uri); -interface Haiku { +interface Movie { title: string; - content: string; + content: string[]; + year: number; + cast: string[]; } async function run() { try { - const database = client.db("insertDB"); + const database = client.db("sample_mflix"); // Specifying a Schema is optional, but it enables type hints on // finds and inserts - const haiku = database.collection("haiku"); - const result = await haiku.insertOne({ - title: "Record of a Shriveled Datum", - content: "No bytes, no problem. Just insert a document, in MongoDB", + const movies = database.collection("movies"); + const result = await movies.insertOne({ + title: "Charade", + genres: ["Comedy", "Romance", "Thriller"], + year: 1963, + cast: ["Cary Grant", "Audrey Hepburn", "Walter Matthau"], }); console.log(`A document was inserted with the _id: ${result.insertedId}`); } finally { diff --git a/source/fundamentals/connection.txt b/source/connect.txt similarity index 61% rename from source/fundamentals/connection.txt rename to source/connect.txt index c768dba01..3efe1f3eb 100644 --- a/source/fundamentals/connection.txt +++ b/source/connect.txt @@ -1,34 +1,35 @@ +.. _node-connect: .. _node-connection: -========== -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 +38,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 ` @@ -57,5 +58,4 @@ Compatibility .. include:: /includes/fact-atlas-link.rst For information about authenticating to MongoDB, -see :ref:`node-authentication-mechanisms` and -:ref:`node-enterprise-authentication-mechanisms`. +see the :ref:`Authentication Mechanisms ` section. diff --git a/source/fundamentals/connection/connection-options.txt b/source/connect/connection-options.txt similarity index 70% rename from source/fundamentals/connection/connection-options.txt rename to source/connect/connection-options.txt index e0f4cb4ff..fbffaa407 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,15 @@ 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 + 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. @@ -43,7 +52,7 @@ string, see :manual:`Connection Strings ` in the - Specifies the authentication mechanism method to use for connection to the server. If you do not specify a value, the driver uses the default mechanism, either ``SCRAM-SHA-1`` or ``SCRAM-SHA-256`` depending on the server version. See - :ref:`authentication mechanism ` for available + the :ref:`Authentication Mechanisms ` section for available authentication mechanisms. * - **authMechanismProperties** @@ -82,9 +91,9 @@ string, see :manual:`Connection Strings ` in the * - **connectTimeoutMS** - non-negative integer - ``30000`` - - Specifies the amount of time, in milliseconds, to wait to establish a single TCP + - Specifies the amount of time in milliseconds to wait to establish a single TCP socket connection to the server before raising an error. Specifying - ``0`` disables the connection timeout. + ``0`` means your application sets an infinite socket timeout when establishing a socket. * - **directConnection** - boolean @@ -246,8 +255,9 @@ string, see :manual:`Connection Strings ` in the * - **socketTimeoutMS** - non-negative integer - ``0`` - - Specifies the amount of time, in milliseconds, spent attempting to send or receive on a - socket before timing out. Specifying ``0`` means no timeout. + - Specifies the amount of time in milliseconds spent attempting to send or receive + on a socket before timing out. Specifying ``0`` means your application sets an + infinite socket timeout when establishing a socket. * - **srvMaxHosts** - non-negative integer @@ -334,6 +344,114 @@ string, see :manual:`Connection Strings ` in the no compression, ``1`` signifies the fastest speed, and ``9`` signifies the best compression. See :ref:`node-network-compression` for more information. +Connection Time Out Options +--------------------------- + +.. list-table:: + :widths: 22 78 + :header-rows: 1 + + * - Setting + - Description + + * - **connectTimeoutMS** + - ``connectTimeoutMS`` is a :ref:`connection option + ` that sets the time, in milliseconds, + for an individual connection from your connection pool to + establish a TCP connection to the {+mdb-server+} before + timing out. To modify the allowed time for + `MongoClient.connect <{+api+}/classes/MongoClient.html#connect>`__ to establish a + connection to a {+mdb-server+}, use the ``serverSelectionTimeoutMS`` option instead. + + **Default:** 30000 + + * - **socketTimeoutMS** + - ``socketTimeoutMS`` specifies the amount of time the driver waits + for an inactive socket before closing it. The default value is to + never time out the socket. This option applies only to sockets that + have already been connected. + + * - **maxTimeMS** + - `maxTimeMS <{+api+}/classes/FindCursor.html#maxTimeMS>`__ + specifies the maximum amount of time that the server + waits for an operation to complete after it has reached the + server. If an operation runs over the specified time limit, it + returns a timeout error. You can pass ``maxTimeMS`` only to an + individual operation or to a cursor. + +To specify the optional settings for your ``MongoClient``, declare one or +more available settings in the ``options`` object of the constructor as +follows: + +.. code-block:: javascript + + const client = new MongoClient(uri, { + connectTimeoutMS: , + socketTimeoutMS: + }); + +To see all the available settings, see the +`MongoClientOptions <{+api+}/interfaces/MongoClientOptions.html>`__ +API Documentation. + +To specify ``maxTimeMS``, pass in the ``maxTimeMS`` method as an option with a timeout +specification to an operation that returns a ``Cursor``: + +.. code-block:: javascript + + const Cursor = collection.distinct('my-key', { maxTimeMS: 50 }); + +Close Sockets After Connection +------------------------------ + +If you experience unexpected network behavior or if a MongoDB process +fails with an error, you might not receive confirmation that the +driver correctly closed the corresponding socket. + +To make sure that the driver correctly closes the socket in these cases, +set the ``socketTimeoutMS`` option. When a MongoDB process times out, the driver +will close the socket. We recommend that you select a value +for ``socketTimeoutMS`` that is two to three times longer than the +expected duration of the slowest operation that your application executes. + +Prevent Long-Running Operations From Slowing Down the Server +------------------------------------------------------------ + +You can prevent long-running operations from slowing down the server by +specifying a timeout value. You can chain the ``maxTimeMS()`` method to +an operation that returns a ``Cursor`` to set a timeout on a specific action. + +The following example shows how you can chain the ``maxTimeMS()`` method +to an operation that returns a ``Cursor``: + +.. literalinclude:: /code-snippets/faq/maxTimeMS-example.js + :language: javascript + +.. _node-faq-keepalive: + +keepAlive Connection Option +--------------------------- + +The ``keepAlive`` connection option specifies whether to enable +:wikipedia:`Transmission Control Protocol (TCP) keepalives +` on a TCP socket. If you enable keepalives, +the driver checks whether the connection is active by sending periodic pings +to your MongoDB deployment. This functionality works only if your +operating system supports the ``SO_KEEPALIVE`` socket option. + +The ``keepAliveInitialDelay`` option specifies the number of +milliseconds that the driver waits before initiating a keepalive. + +The 5.3 driver version release deprecated these options. Starting in +version 6.0 of the driver, the ``keepAlive`` option is permanently set +to ``true``, and the ``keepAliveInitialDelay`` is set to 300000 +milliseconds (300 seconds). + +.. warning:: + + If your firewall ignores or drops the keepalive messages, you might + not be able to identify dropped connections. + Additional Information ---------------------- diff --git a/source/connect/connection-options/connection-pools.txt b/source/connect/connection-options/connection-pools.txt new file mode 100644 index 000000000..f70abd878 --- /dev/null +++ b/source/connect/connection-options/connection-pools.txt @@ -0,0 +1,279 @@ +.. _node-connection-pools: + +======================================== +Manage Connections with 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+}. + +.. _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/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/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..20e3d09e2 --- /dev/null +++ b/source/connect/connection-targets.txt @@ -0,0 +1,111 @@ +.. _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 + +.. _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>`__ . diff --git a/source/connection-troubleshooting.txt b/source/connect/connection-troubleshooting.txt similarity index 70% rename from source/connection-troubleshooting.txt rename to source/connect/connection-troubleshooting.txt index db3f56544..ece0d8487 100644 --- a/source/connection-troubleshooting.txt +++ b/source/connect/connection-troubleshooting.txt @@ -26,59 +26,51 @@ using the {+driver-long+} to connect to a MongoDB deployment. This page addresses only connection issues. If you encounter any other issues with MongoDB or the driver, visit the following resources: - - The :ref:`Frequently Asked Questions (FAQ) ` for the - {+driver-short+} - The :ref:`Issues & Help ` page, which has - information about reporting bugs, contributing to the driver, and - finding more resources + information about how to report bugs, contribute to the driver, and + find more resources - The `MongoDB Community Forums `__ for questions, discussions, or general technical support Connection Error -~~~~~~~~~~~~~~~~ +---------------- -The following error message indicates that the driver cannot connect to a server -on the specified hostname or port. Multiple situations can generate this error -message. In this sample error message, the hostname is ``127.0.0.1`` and the -port is ``27017``: - -.. code-block:: none - :copyable: false - - Error: couldn't connect to server 127.0.0.1:27017 +If the driver cannot connect to the specified host, you might get an +``MongoServerSelectionError``. The following sections describe actions you can take to potentially resolve the issue. -.. _node-troubleshooting-connection-string-port: - -Check Your Connection String ----------------------------- - -Verify that the hostname and port number in the connection string are both -accurate. The default port value for a MongoDB instance is -``27017``, but you can configure MongoDB to communicate on another port. - .. _node-troubleshooting-connection-firewall: Configure Your Firewall ------------------------ +~~~~~~~~~~~~~~~~~~~~~~~ Verify that the ports your MongoDB deployment listens on are not blocked by a firewall on the same network. MongoDB uses port ``27017`` by default. To learn more about the default ports MongoDB uses and how to change them, see -:manual:`Default MongoDB Port `. +:manual:`Default MongoDB Port ` in the +{+mdb-server+} manual. .. warning:: Do not open a port in your firewall unless you are sure it's the port used by your MongoDB deployment. +Check Your Network Access List +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Verify that your IP Address is listed in the IP Access List for your cluster. +You can find your IP Access List in the Network Access section of +the Atlas UI. To learn more about how to configure your IP Access List, +see the :atlas:`Configure IP Access List Entries ` +guide in the Atlas documentation. + ECONNREFUSED Error -~~~~~~~~~~~~~~~~~~ +------------------ If the connection is refused when the driver attempts to connect to the MongoDB -instance, it generates this error message: +instance, it generates an error message similar to the following: .. code-block:: none :copyable: false @@ -88,8 +80,8 @@ instance, it generates this error message: The following sections describe actions you can take to potentially resolve the issue. -Ensure MongoDB and Your Client Use the Same Protocol ----------------------------------------------------- +Ensure MongoDB and Your Client Use the Same IP Address +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In Node.js v17 and later, the DNS resolver uses ``IPv6`` by default when both the client and host support both. For example, if MongoDB uses IPv4 and your @@ -112,10 +104,10 @@ specifying ``family: 4`` as an }); ECONNRESET Error -~~~~~~~~~~~~~~~~ +---------------- If the connection is reset when the driver calls ``client.connect()``, it -generates this error message: +generates an error message similar to the following: .. code-block:: none :copyable: false @@ -125,7 +117,7 @@ generates this error message: The following section describes a method that may help resolve the issue. Control the Number of File Descriptors --------------------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A file descriptor is a unique identifier associated with an open process. In most operating systems, each open connection from the driver is associated with a @@ -136,14 +128,16 @@ if the number of connections exceeds this limit. You can set the maximum number of connections by setting ``maxPoolSize``. To resolve this error, you can decrease the number of maximum allowed connections by setting the value of ``maxPoolSize``. Alternatively, you could increase the -file descriptor limit in your operating system. +file descriptor limit in your operating system. To learn more about how to set +``maxPoolSize``, see the API documentation for +`maxPoolSize <{+api+}/interfaces/MongoClientOptions.html#maxPoolSize>`__ . .. warning:: Always be cautious when changing the configuration of your operating system. Authentication Error -~~~~~~~~~~~~~~~~~~~~ +-------------------- The {+driver-short+} can fail to connect to a MongoDB instance if the authorization is not configured correctly. If you are using ``SCRAM-SHA-256`` @@ -153,8 +147,7 @@ error message similar to one of the following messages: .. code-block:: none :copyable: false - Command failed with error 18 (AuthenticationFailed): 'Authentication - failed.' on server :. + MongoServerError: bad auth : authentication failed .. code-block:: none :copyable: false @@ -169,15 +162,16 @@ issue. .. _node-troubleshooting-connection-string-auth: Check Your Connection String ----------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ An invalid connection string is the most common cause of authentication -issues when attempting to connect to MongoDB using ``SCRAM-SHA-256``. +issues when you attempt to connect to MongoDB by using ``SCRAM-SHA-256``. .. tip:: For more information about connection strings, - see :ref:`Connection URI ` in the Connection Guide. + see the :ref:`Connection URI ` section in the Connection + Guide. If your connection string contains a username and password, ensure that they are in the correct format. If the username or password includes any of the @@ -203,7 +197,7 @@ This results in the following output: .. _node-troubleshooting-connection-admin: Verify the User Is in the Authentication Database -------------------------------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To successfully authenticate a connection by using a username and password with ``SCRAM-SHA-256``, the username must be defined in the authentication database. @@ -219,12 +213,8 @@ database: const uri = "mongodb://:@:/?authSource=users"; const client = new MongoClient(uri); -You can check if this is the issue by attempting to connect to a MongoDB -instance hosted on the local machine with the same code. A deployment on -the same machine doesn't require any authorization to connect. - Error Sending Message -~~~~~~~~~~~~~~~~~~~~~ +--------------------- When the driver fails to send a command after you make a request, it may display the following error message: @@ -238,7 +228,7 @@ The following sections describe actions you can take to potentially resolve the issue. Check the User Permissions --------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~ Verify that you've accessed the MongoDB deployment with the correct user. The term "message" in the error can be a command sent by the driver. @@ -251,7 +241,7 @@ to a MongoDB deployment. For more information about how to configure RBAC in Mon see :manual:`Default MongoDB Port `. Configure Your Firewall ------------------------ +~~~~~~~~~~~~~~~~~~~~~~~ The firewall needs to have an open port for communicating with the MongoDB instance. For more information about configuring the firewall, see @@ -261,7 +251,7 @@ the Connection Error section. .. _node-troubleshooting-connection-number-connections: Check the Number of Connections -------------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Each ``MongoClient`` instance supports a maximum number of concurrent open connections in its connection pool. You can configure the parameter ``maxPoolSize`` @@ -270,33 +260,12 @@ number of open connections equal to ``maxPoolSize``, the server waits until a connection becomes available. If this wait time exceeds the ``maxIdleTimeMS`` value, the driver responds with an error. -For more information about how connection pooling works, see -:ref:`How Does Connection Pooling Work in the Node Driver? ` -in the FAQ. - -Too Many Open Connections -~~~~~~~~~~~~~~~~~~~~~~~~~ - -The driver creates the following error message when it attempts to open a -connection, but it's reached the maximum number of connections: - -.. code-block:: none - :copyable: false - - connection refused because too many open connections - -The following section describes a method that may help resolve the issue. - -Check the Number of Connections -------------------------------- - -To create more open connections, increase the value of ``maxPoolSize``. For more -information about checking the number of connections, see -:ref:`Check the Number of Connections ` -in the Error Sending Message section. +For more information about how connection pooling works, see the +:ref:`Connection Pool Overview ` +in the Connection Pools page. Timeout Error -~~~~~~~~~~~~~ +------------- When the network is not able to deliver a request from the driver to the server quickly enough, it can time out. When this happens, you might receive an error message @@ -311,12 +280,12 @@ If you receive this error, try the following action to resolve the issue. Set connectTimeoutMS --------------------- +~~~~~~~~~~~~~~~~~~~~ The driver may hang when it's unable to establish a connection because it takes too long attempting to reach unreachable replica set nodes. You can limit the time the driver spends attempting to establish the connection by using the -``connectTimeMS`` setting. To learn more about this setting, see the +``connectTimeoutMS`` setting. To learn more about this setting, see the :manual:`Timeout Options ` in the Server manual. @@ -334,10 +303,66 @@ The following example sets ``connectTimeoutMS`` to 10000 milliseconds. connectTimeoutMS: 10000, }); -Check the Number of Connections -------------------------------- +Client Disconnect While Running Operation +----------------------------------------- -The number of connections to the server may exceed ``maxPoolSize``. For more -information about checking the number of connections, see -:ref:`Check the Number of Connections ` -in the Error Sending Message section. +Starting in {+mdb-server+} version 4.2, the server terminates +running operations such as aggregations and find operations if the +client disconnects. + +Other operations, such as write operations, continue to run on the +{+mdb-server+} even if the client disconnects. This behavior can cause data +inconsistencies if your application retries the operation after the +client disconnects. + +Unexpected Network Behavior +--------------------------- + +You might experience unexpected network behavior if the firewall between +your application and MongoDB is misconfigured. These firewalls can be +overly aggressive in their removal of connections, which can lead to +unexpected errors. + +Confirm that your firewall exhibits the following behavior: + +- The firewall sends a ``FIN`` packet when closing a connection, + informing the driver that the socket is closed. + +- The firewall allows keepalive messages. + +.. tip:: + + To learn more about keepalive messages, see the :ref:`keepAlive Connection Option + ` section in the Connection Options page. + +Connection String Errors for Replica Sets +----------------------------------------- + +The connection string passed to the driver must use exact hostnames for +the servers, as set in the :manual:`Replica Set Config `. +Given the following configuration settings for your replica set, in +order for the replica set discovery and :manual:`failover +` to work, the driver must have access +to ``server1``, ``server2``, and ``server3``. + +.. code-block:: JSON + + { + "_id": "testSet", + "version": 1, + "protocolVersion": 1, + "members": [ + { + "_id": 1, + "host": "server1:31000" + }, + { + "_id": 2, + "host": "server2:31001" + }, + { + "_id": 3, + "host": "server3:31002" + } + ] + } \ No newline at end of file diff --git a/source/connect/mongoclient.txt b/source/connect/mongoclient.txt new file mode 100644 index 000000000..f1b27a261 --- /dev/null +++ b/source/connect/mongoclient.txt @@ -0,0 +1,181 @@ +.. _node-mongoclient: + +==================== +Create a MongoClient +==================== + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :description: Learn how to create a MongoClient using the {+driver-short+}. + :keywords: connection string, URI, server, Atlas, settings, client + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +To connect to a MongoDB deployment, you need two things: + +- **Connection URI**, also known as a *connection string*, which tells the + {+driver-short+} which MongoDB deployment to connect to. +- **MongoClient** object, which creates the connection to and performs + operations on the MongoDB deployment. + +You can also use ``MongoClientOptions`` to customize the way the {+driver-short+} behaves +while connected to MongoDB. + +This guide shows you how to create a connection string and use a ``MongoClient`` object +to connect to MongoDB. + +.. _node-connection-uri: + +Connection URI +-------------- + +A standard connection string includes the following components: + +.. list-table:: + :widths: 20 80 + :header-rows: 1 + + * - Component + - Description + + * - ``mongodb://`` + + - Required. A prefix that identifies this as a string in the + standard connection format. + + * - ``username:password`` + + - Optional. Authentication credentials. If you include these, the client + authenticates the user against the database specified in ``authSource``. + For more information about the ``authSource`` connection option, + see :ref:`node-troubleshooting-connection-admin` in the Connection Troubleshooting guide. + + * - ``host[:port]`` + + - Required. The host and optional port number where MongoDB is running. If you don't + include the port number, the driver uses the default port, ``27017``. + + * - ``/defaultauthdb`` + + - Optional. The authentication database to use if the + connection string includes ``username:password@`` + authentication credentials but not the ``authSource`` option. + When you call ``client.db()`` with no argument, this is the database that is used. If you don't include + this component, the client authenticates the user against the ``admin`` database. + + * - ``?`` + + - Optional. A query string that specifies connection-specific + options as ``=`` pairs. See + :ref:`node-connection-options` for a full description of + these options. + +For more information about creating a connection string, see +:manual:`Connection Strings ` in the +MongoDB Server documentation. + +.. _connect-sample-node-driver: + +Atlas Connection Example +------------------------ + +You must create a client to connect to a MongoDB deployment on Atlas. To create +a client, construct an instance of ``MongoClient``, passing in your +URI and a ``MongoClientOptions`` object. + +.. tip:: Reuse Your Client + + As each ``MongoClient`` represents a pool of connections to the + database, most applications only require a single instance of a + ``MongoClient``, even across multiple requests. To learn more about + how connection pools work in the driver, see the :ref:`Connection Pools page + `. + +Use the ``serverApi`` option in your ``MongoClientOptions`` object to +enable the {+stable-api+} feature, which forces the server to run operations +with behavior compatible with the specified API version. + +The following code shows how you can specify the connection string and the +{+stable-api+} client option when connecting to a MongoDB deployment on Atlas and +verify that the connection is successful: + +.. literalinclude:: /code-snippets/connection/stable-api-connect.js + :language: javascript + +.. note:: + + The {+driver-short+} automatically calls the ``MongoClient.connect()`` + method when using the client to perform CRUD operations on your MongoDB deployment. + Call the ``MongoClient.connect()`` method explicitly if you want to verify that the + connection is successful. + +To learn more about the {+stable-api+} feature, see the :ref:`{+stable-api+} page +`. + +Prevent a Slow Operation From Delaying Other Operations +------------------------------------------------------- + +When you use the same ``MongoClient`` instance to run multiple MongoDB +operations concurrently, a slow operation can cause delays to other +operations. Slow operations keep a connection to MongoDB occupied, +which can cause other operations to wait until another connection +becomes available. + +If you suspect that slow MongoDB operations are causing delays, you +can check the performance of all in-progress operations by using the +following methods: + +- Enable the database profiler on your deployment. To learn more, see + :manual:`Database Profiler ` + in the Server manual. +- Run the ``db.currentOp()`` MongoDB Shell command. To learn more, see the + :manual:`db.currentOp() ` + documentation in the Server manual. +- Enable connection pool monitoring. To learn more, see + :ref:`node-connection-pool-monitoring`. + +After you determine which operations are causing delays, try to improve +the performance of these operations. Read the :website:`Best Practices +Guide for MongoDB Performance ` for possible solutions. + +If you implement performance best practices but still +experience delays, you can modify your connection settings to increase +the size of the connection pool. A connection pool is the group of +connections to the server that the driver maintains at any time. + +To specify the maximum size of a +connection pool, you can set the ``maxPoolSize`` option in the +:ref:`connection options ` for your +``MongoClient`` instance. The default value +of ``maxPoolSize`` is ``100``. If the number of in-use connections to a +server reaches ``maxPoolSize``, the next operation sent to the server +pauses until a connection to the driver becomes available. The following +code sets ``maxPoolSize`` to ``150`` when creating a new ``MongoClient``: + +.. code-block:: js + + const client = new MongoClient(uri, { maxPoolSize: 150 }); + +.. tip:: + + To learn more about connection pooling, see the :ref:`Connection Pool Overview + ` section in the Connection Pools page. + +API Documentation +----------------- + +For more information about creating a ``MongoClient`` object with the +{+driver-short+}, see the following API documentation: + +- `MongoClient <{+api+}/classes/MongoClient.html>`__ +- `MongoClientOptions <{+api+}/interfaces/MongoClientOptions.html>`__ \ No newline at end of file diff --git a/source/crud.txt b/source/crud.txt new file mode 100644 index 000000000..5afe449d3 --- /dev/null +++ b/source/crud.txt @@ -0,0 +1,49 @@ +.. _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 + Generate Custom _id Values + Store Large Files + +CRUD (Create, Read, Update, Delete) operations enable you to work with +data stored in MongoDB. + +- :ref:`node-insert` +- :ref:`node-query` +- :ref:`node-update` +- :ref:`node-delete` +- :ref:`node-bulk-write` +- :ref:`node-crud-compound-operations` +- :ref:`node-transactions` +- :ref:`node-configure` +- :ref:`node-pkfactory` +- :ref:`node-gridfs` \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations/bulk.txt b/source/crud/bulk-write.txt similarity index 93% rename from source/fundamentals/crud/write-operations/bulk.txt rename to source/crud/bulk-write.txt index 7cba6ee8a..62a65590a 100644 --- a/source/fundamentals/crud/write-operations/bulk.txt +++ b/source/crud/bulk-write.txt @@ -1,3 +1,4 @@ +.. _node-bulk-write: .. _node-fundamentals-bulk: =============== @@ -10,6 +11,14 @@ Bulk Operations :depth: 2 :class: singlecol +.. facet:: + :name: genre + :values: reference + +.. meta:: + :description: Learn how to perform bulk operations by using the {+driver-long+}. + :keywords: insert, update, replace, code example, efficiency + Overview -------- @@ -220,7 +229,7 @@ The following table describes the fields that you can set in a * - ``collation`` - | (Optional) The collation to use when sorting results. To learn more - about collations, see the :ref:`node-fundamentals-collations` guide. + about collations, see the :ref:`node-collations` section of the :ref:`node-configure` guide. | Type: ``String`` or ``Object`` * - ``hint`` @@ -299,7 +308,7 @@ The following table describes the fields that you can set in a * - ``collation`` - | (Optional) The collation to use when sorting results. To learn more - about collations, see the :ref:`node-fundamentals-collations` guide. + about collations, see the :ref:`node-collations` section of the :ref:`node-configure` guide. | Type: ``String`` or ``Object`` * - ``hint`` @@ -387,7 +396,7 @@ The following table describes the fields you can set in an ``UpdateOneModel`` or * - ``collation`` - | (Optional) The collation to use when sorting results. To learn more about - collations, see the :ref:`node-fundamentals-collations` guide. + collations, see the :ref:`node-collations` section of the :ref:`node-configure` guide. | Type: ``Object`` * - ``hint`` @@ -474,7 +483,7 @@ to specify an update operation: * - ``collation`` - | (Optional) The collation to use when sorting results. To learn more about - collations, see the :ref:`node-fundamentals-collations` guide. + collations, see the :ref:`node-collations` section of the :ref:`node-configure` guide. | Type: ``Document`` * - ``hint`` @@ -558,7 +567,7 @@ The following table describes the fields you can set in a ``DeleteOneModel`` or * - ``collation`` - | (Optional) The collation to use when sorting results. To learn more about - collations, see the :ref:`node-fundamentals-collations` guide. + collations, see the :ref:`node-collations` section of the :ref:`node-configure` guide. | Type: ``Object`` * - ``hint`` @@ -635,7 +644,7 @@ to specify a delete operation: * - ``collation`` - | (Optional) The collation to use when sorting results. To learn more about - collations, see the :ref:`node-fundamentals-collations` guide. + collations, see the :ref:`node-collations` section of the :ref:`node-configure` guide. | Type: ``Document`` Example @@ -823,6 +832,52 @@ A ``MongoClientBulkWriteError`` object contains the following properties: progress before the error. | Type: ``ClientBulkWriteResult`` +.. _node-usage-bulk: + +bulkWrite() Example: Full File +------------------------------ + +.. include:: /includes/crud/example-intro.rst + +The following code is a complete, standalone file that performs a bulk write +operation on the ``theaters`` collection in the ``sample_mflix`` database. The +``operations`` parameter includes examples of ``insertOne``, +``updateMany``, and ``deleteOne`` write operations: + +.. tabs:: + + .. tab:: JavaScript + :tabid: javascript + + .. literalinclude:: /code-snippets/usage-examples/bulkWrite.js + :language: javascript + :linenos: + + .. tab:: TypeScript + :tabid: typescript + + .. literalinclude:: /code-snippets/usage-examples/bulkWrite.ts + :language: typescript + :linenos: + +Running the preceding example results in the following output: + +.. code-block:: javascript + :copyable: false + + BulkWriteResult { + insertedCount: 2, + matchedCount: 1, + modifiedCount: 1, + deletedCount: 0, + upsertedCount: 0, + upsertedIds: {}, + insertedIds: { + '0': new ObjectId("..."), + '1': new ObjectId("...") + } + } + .. _node-bulk-addtl-info: Additional Information 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..92748c8f9 --- /dev/null +++ b/source/crud/configure.txt @@ -0,0 +1,358 @@ +.. _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 use the {+driver-short+} to configure read +and write operations. + +Read and Write Settings +----------------------- + +You can control how the driver routes read operations by setting a **read preference**. +You can also control how the driver handles data consistency and durability by setting +a **read concern** or **write concern**. Read concerns specify the level of durability +required for the data when performing read operations, and write concerns specify +how the driver waits for acknowledgment of write operations on a replica set. + +You can set write concern, read concern, and read preference options at the following +levels: + +- Client, which sets the *default for all operation executions* unless overridden +- Transaction +- Database +- Collection + +The preceding list also indicates the increasing order of precedence of the option settings. For +example, if you set a read concern level for a transaction, it will override a read +concern level set for the client. + +.. tip:: + + To learn more about the read and write settings, see the following guides in the + {+mdb-server+} manual: + + - :manual:`Read Preference ` + - :manual:`Read Concern ` + - :manual:`Write Concern ` + +This section shows how to configure your read and write settings at each level. + +Client Configuration +~~~~~~~~~~~~~~~~~~~~ + +This example shows how to set the read preference, read concern, and +write concern of a ``MongoClient`` instance by passing a ``MongoClientOptions`` +object to the constructor. The code configures the following settings: + +- ``SECONDARY`` read preference: Read operations retrieve data from + secondary replica set members +- ``local`` read concern: Read operations return the instance's most recent data + without guaranteeing that the data has been written to a majority of the replica + set members +- ``2`` write concern: The primary and one secondary replica set member + must acknowledge the write operation + +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-client-settings + :end-before: end-client-settings + +Alternatively, you can specify the read and write settings in the connection +URI, which is passed as a parameter to the ``MongoClient`` constructor: + +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-client-settings-uri + :end-before: end-client-settings-uri + +.. _node-read-write-transaction: + +Transaction Configuration +~~~~~~~~~~~~~~~~~~~~~~~~~ + +This example shows how to set the read preference, read concern, and +write concern of a transaction by passing a ``TransactionOptions`` object +to the ``startTransaction()`` method. The code configures the following settings: + +- ``PRIMARY`` read preference: Read operations retrieve data from + the primary replica set member +- ``majority`` read concern: Read operations return the instance's most recent data + that has been written to a majority of replica set members +- ``1`` write concern: The primary replica set member must acknowledge the + write operation + +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-transaction-settings + :end-before: end-transaction-settings + +.. _node-read-write-database: + +Database Configuration +~~~~~~~~~~~~~~~~~~~~~~ + +This example shows how to set the read preference, read concern, and +write concern of a database called ``test_database`` by passing a ``DbOptions`` +object to the ``db()`` method. The code configures the following settings: + +- ``PRIMARY_PREFERRED`` read preference: Read operations retrieve data from + the primary replica set member, or secondary members if the primary is unavailable +- ``available`` read concern: Read operations return the instance's most recent data + without guaranteeing that the data has been written to a majority of the replica + set members +- ``majority`` write concern: The majority of all replica set members + must acknowledge the write operation + +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-database-settings + :end-before: end-database-settings + +.. _node-read-write-collection: + +Collection Configuration +~~~~~~~~~~~~~~~~~~~~~~~~ + +This example shows how to set the read preference, read concern, and +write concern of a collection called ``test_collection`` by passing a ``CollectionOptions`` +object to the ``collection()`` method. The code configures the following settings: + +- ``SECONDARY_PREFERRED`` read preference: Read operations retrieve data from + secondary replica set members, or the primary members if no secondaries are available +- ``available`` read concern: Read operations return the instance's most recent data + without guaranteeing that the data has been written to a majority of the replica + set members +- ``0`` write concern: Does not request acknowledgment of the write operation + +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-collection-settings + :end-before: end-collection-settings + +Tag Sets +-------- + +In {+mdb-server+}, you can apply key-value :manual:`tags +` to replica-set +members according to any criteria you choose. You can then use +those tags to target one or more members for a read operation. + +By default, the {+driver-short+} ignores tags when choosing a member +to read from. To instruct the {+driver-short+} to prefer certain tags, +pass them as a parameter to your read preference class +constructor. + +This code example sets the ``readPreference`` option to a tag set that +instructs ``test_database`` to prefer reads from secondary replica set +members in the following order: + +1. Members from the New York data center (``{ dc: 'ny' }``) +#. Members from the San Francisco data center (``{ dc: 'sf' }``) +#. Any secondary members (``{}``) + +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-tag-set + :end-before: end-tag-set + +Local Threshold +--------------- + +If multiple replica-set members match the read preference and tag sets you specify, +the {+driver-short+} reads from the nearest replica set members, chosen according to +their ping time. + +By default, the driver uses only those members whose ping times are within 15 milliseconds +of the nearest member for queries. To distribute reads between members with +higher latencies, pass the ``localThresholdMS`` option to the ``MongoClient()`` constructor. + +The following example specifies a local threshold of 35 milliseconds: + +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-local-threshold + :end-before: end-local-threshold + +In the preceding example, the {+driver-short+} distributes reads between matching members +within 35 milliseconds of the closest member's ping time. + +.. note:: + + The {+driver-short+} ignores the value of ``localThresholdMS`` when communicating with a + replica set through a ``mongos`` instance. In this case, use the + :manual:`localThreshold ` + command-line option. + +.. _node-fundamentals-collations: +.. _node-collations: + +Collation +--------- + +You can specify a **collation** to modify the behavior of read +and write operations. A collation is a set of language-specific rules for string +comparison, such as for letter case and accent marks. + +MongoDB sorts strings using *binary collation* by default. This default +collation 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, and you can choose to apply a different set of collation rules +to your operation. + +You can specify a collation at the following levels: + +- Collection: Sets the default collation for operations on the collection. + You cannot define a collation for an existing collection. + +- Index: Sets the collation for operations that use the index. + +- Operation: Sets the operation's collation and overrides any inherited collations. + +.. _node-configure-collation-fields: + +Collation Fields +~~~~~~~~~~~~~~~~ + +The collation object contains the following fields: + +.. code-block:: javascript + + collation: { + locale: , + caseLevel: , + caseFirst: , + strength: , + numericOrdering: , + alternate: , + maxVariable: , + backwards: + } + +When setting the ``collation`` option, you must specify the ``locale`` field. +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 +` +in the {+mdb-server+} manual. + +.. _node-configure-collation-exs: + +Collation Examples +~~~~~~~~~~~~~~~~~~ + +To specify a collation, create a ``collation`` object and set its +``locale`` field to the language collation you want to use. Then, +pass this object as an options parameter to the method corresponding +to the target collation level. + +This section includes examples that set collations at the collection, +index, and operation levels. + +.. _node-configure-collation-coll-index: + +Set Collection and Index Collations +``````````````````````````````````` + +The following example creates a new collection named ``names`` +and sets its default collation to the ``"fr_CA"`` locale: + +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-collection-collation + :end-before: end-collection-collation + +You can create an index on the ``names`` collection that specifies a different +collation, as shown in the following example: + +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-index-collation + :end-before: end-index-collation + +Set an Operation Collation +`````````````````````````` + +You can run an operation on the ``names`` collection, created in +the :ref:`preceding section `, that overrides +the default collation. + +The ``names`` collection contains the following documents: + +.. code-block:: none + + { "_id" : 1, "first_name" : "Hans", "last_name" : "Muller" } + { "_id" : 2, "first_name" : "Gunter", "last_name" : "Braun" } + { "_id" : 3, "first_name" : "Günter", "last_name" : "Krause" } + { "_id" : 4, "first_name" : "Jürgen", "last_name" : "Weber" } + +This example calls the ``findOneAndUpdate()`` method to update +the first matching document that has a ``first_name`` value of ``"Gunter"``. +The code applies a collation with the ``"de"`` locale and the ``"phonebook"`` +locale variant: + +.. literalinclude:: /includes/fundamentals/configure.js + :language: javascript + :dedent: + :start-after: start-operation-collation + :end-before: end-operation-collation + +In the preceding example, the ``phonebook`` locale variant instructs +the driver to sort characters with umlauts before the same characters without +umlauts. As a result, the operation matches the document that has +a ``first_name`` value of ``"Günter"``, with an umlaut, and returns +the following update information: + +.. code-block:: none + :copyable: false + + { lastErrorObject: { updatedExisting: true, n: 1 }, + value: { _id: 3, first_name: 'Günter', last_name: 'Krause' }, + ok: 1 } + +.. tip:: + + To learn more about locale variants, see :manual:`Local Variants ` + in the {+mdb-server+} manual. + +API Documentation +----------------- + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- `MongoClient <{+api+}/classes/MongoClient.html>`__ +- `Db <{+api+}/classes/Db.html>`__ +- `Collection <{+api+}/classes/Collection.html>`__ +- `MongoClientOptions <{+api+}/interfaces/MongoClientOptions.html>`__ +- `ClientSessionOptions <{+api+}/interfaces/ClientSessionOptions.html>`__ +- `TransactionOptions <{+api+}/interfaces/TransactionOptions.html>`__ +- `DbOptions <{+api+}/interfaces/DbOptions.html>`__ +- `CollectionOptions <{+api+}/interfaces/CollectionOptions.html>`__ +- `collation <{+api+}/interfaces/CreateCollectionOptions.html#collation>`__ \ No newline at end of file diff --git a/source/crud/delete.txt b/source/crud/delete.txt new file mode 100644 index 000000000..fdc804afd --- /dev/null +++ b/source/crud/delete.txt @@ -0,0 +1,162 @@ +.. _node-fundamentals-delete: +.. _node-delete: + +================ +Delete Documents +================ + +.. meta:: + :description: Learn how to use deleteOne() and deleteMany() methods in the MongoDB Node.js Driver to remove documents from a collection based on specified query criteria. + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example, node.js, delete data + +Overview +-------- + +In this section, we show you how to call the write operations to **remove** +documents from a collection in your MongoDB database. + +Delete +------ + +If you want to remove existing documents from a collection, you can +use ``deleteOne()`` to remove one document or ``deleteMany()`` for one or +more documents. These methods accept a query document that matches the +documents you want to delete. + +.. note:: + + If your application uses information about the deleted document after deletion, + you can use the + `collection.findOneAndDelete() <{+api+}/classes/Collection.html#findOneAndDelete>`__ + method, which has a similar interface to ``deleteOne()`` but also + returns the deleted document. + +You can specify the document or documents to be deleted by the +``deleteOne()`` or ``deleteMany()`` write operations in a JSON object as +follows: + +.. code-block:: javascript + + const doc = { + pageViews: { + $gt: 10, + $lt: 32768 + } + }; + +To delete the first matching document using the ``deleteOne()`` method or +to delete all matching documents using the ``deleteMany()`` method, pass the +document as the method parameter: + +.. code-block:: javascript + + const deleteResult = await myColl.deleteOne(doc); + const deleteManyResult = await myColl.deleteMany(doc); + +You can print the number of documents deleted by the operation by +accessing the ``deletedCount`` field of the result for each of the +method calls above as follows: + +.. code-block:: javascript + + console.dir(deleteResult.deletedCount); + console.dir(deleteManyResult.deletedCount); + +If the delete operation is successful, these statements print the number of documents +deleted by the associated operation. + +.. _node-usage-deleteone: + +deleteOne() Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. include:: /includes/crud/example-intro.rst + +.. include:: /includes/crud/example-identical-code.rst + +The following code is a complete, standalone file that performs a delete one +operation: + +.. literalinclude:: /code-snippets/usage-examples/deleteOne.js + :language: javascript + :linenos: + +Running the preceding example results in the following output: + +.. code-block:: none + :copyable: false + + Successfully deleted one document. + +If you run the example more than once, the code produces the following output +because you deleted the matching document in the first run: + +.. code-block:: none + :copyable: false + + No documents matched the query. Deleted 0 documents. + +.. _node-usage-deletemany: + +deleteMany() Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. include:: /includes/crud/example-intro.rst + +The following code is a complete, standalone file that performs a delete many +operation: + +.. tabs:: + + .. tab:: JavaScript + :tabid: javascript + + .. literalinclude:: /code-snippets/usage-examples/deleteMany.js + :language: javascript + :linenos: + + .. tab:: TypeScript + :tabid: typescript + + .. literalinclude:: /code-snippets/usage-examples/deleteMany.ts + :language: typescript + :linenos: + +Running the preceding example for the first time results in the following output: + +.. code-block:: none + :copyable: false + + Deleted 19 documents + +If you run the example more than once, you see the following output because +you deleted the matching documents in the first run: + +.. code-block:: none + :copyable: false + + Deleted 0 documents + +API Documentation +----------------- + +To learn more about any of the types or methods discussed in this guide, see the +following API documentation: + +- `MongoClient <{+api+}/classes/MongoClient.html>`__ +- `Db <{+api+}/classes/Db.html>`__ +- `Collection <{+api+}/classes/Collection.html>`__ +- `deleteOne() <{+api+}/classes/Collection.html#deleteOne>`__ +- `deleteMany() <{+api+}/classes/Collection.html#deleteMany>`__ \ No newline at end of file diff --git a/source/fundamentals/gridfs.txt b/source/crud/gridfs.txt similarity index 98% rename from source/fundamentals/gridfs.txt rename to source/crud/gridfs.txt index 514f300b6..0f604d50f 100644 --- a/source/fundamentals/gridfs.txt +++ b/source/crud/gridfs.txt @@ -1,8 +1,8 @@ .. _node-gridfs: -====== -GridFS -====== +============================= +Store Large Files with GridFS +============================= .. facet:: :name: genre @@ -167,8 +167,8 @@ 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 ` +- :ref:`Access Data From a Cursor guide ` +- :ref:`Find Documents guide ` .. _gridfs-download-files: diff --git a/source/fundamentals/crud/write-operations/insert.txt b/source/crud/insert.txt similarity index 79% rename from source/fundamentals/crud/write-operations/insert.txt rename to source/crud/insert.txt index d6da4aa81..c60b916a2 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 @@ -15,7 +16,7 @@ Insert Documents .. contents:: On this page :local: :backlinks: none - :depth: 1 + :depth: 2 :class: singlecol Overview @@ -45,8 +46,8 @@ operations: full-screen button (:guilabel:`⛶`) in the top-right corner of the lab pane. The following sections focus on ``insertOne()`` and ``insertMany()``. For an -example on how to use the ``bulkWrite()`` method, see our runnable :doc:`Bulk -Operations Example `. +example on how to use the ``bulkWrite()`` method, see the :ref:`node-usage-bulk` +section of the :ref:`node-bulk-write` guide. .. _id-note: @@ -114,7 +115,39 @@ section, see the following resources: - API Documentation on `insertOne() <{+api+}/classes/Collection.html#insertOne>`__ - API Documentation on `InsertOneResult <{+api+}/interfaces/InsertOneResult.html>`__ - Server manual entry on :manual:`insertOne() ` -- Runnable :doc:`Insert a Document Example ` + +.. _node-usage-insert: + +insertOne() Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. include:: /includes/crud/example-intro.rst + +The following code is a complete, standalone file that performs an insert one +operation: + +.. tabs:: + + .. tab:: JavaScript + :tabid: javascript + + .. literalinclude:: /code-snippets/usage-examples/insertOne.js + :language: javascript + :linenos: + + .. tab:: TypeScript + :tabid: typescript + + .. literalinclude:: /code-snippets/usage-examples/insertOne.ts + :language: typescript + :linenos: + +Running the preceding example results in the following output: + +.. code-block:: none + :copyable: false + + A document was inserted with the _id: ... Insert Multiple Documents ------------------------- @@ -239,10 +272,54 @@ section, see the following resources: - API Documentation on `InsertManyResult <{+api+}/interfaces/InsertManyResult.html>`__ - API Documentation on `PkFactory <{+api+}/interfaces/PkFactory.html>`__ - Server manual entry on :manual:`insertMany() ` -- Runnable :doc:`Insert Multiple Documents Example ` + +.. _node-usage-insertmany: + +insertMany() Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. include:: /includes/crud/example-intro.rst + +The following code is a complete, standalone file that performs an insert many +operation: + +.. tabs:: + + .. tab:: JavaScript + :tabid: javascript + + .. literalinclude:: /code-snippets/usage-examples/insertMany.js + :language: javascript + :linenos: + + .. tab:: TypeScript + :tabid: typescript + + .. literalinclude:: /code-snippets/usage-examples/insertMany.ts + :language: typescript + :linenos: + +Running the preceding example results in the following output: + +.. code-block:: none + :copyable: false + + 3 documents were inserted .. _node-insert-instruqt-lab: .. instruqt:: /mongodb-docs/tracks/insert-node?token=em_S6rjcmIzxGB4Sz_y :title: insertOne() Lesson :drawer: + +API Documentation +----------------- + +To learn more about any of the types or methods discussed in this guide, see the +following API documentation: + +- `MongoClient <{+api+}/classes/MongoClient.html>`__ +- `Db <{+api+}/classes/Db.html>`__ +- `Collection <{+api+}/classes/Collection.html>`__ +- `insertOne() <{+api+}/classes/Collection.html#insertOne>`__ +- `insertMany() <{+api+}/classes/Collection.html#insertMany>`__ \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations/pkFactory.txt b/source/crud/pkFactory.txt similarity index 96% rename from source/fundamentals/crud/write-operations/pkFactory.txt rename to source/crud/pkFactory.txt index 37456e967..34a71eb44 100644 --- a/source/fundamentals/crud/write-operations/pkFactory.txt +++ b/source/crud/pkFactory.txt @@ -1,8 +1,8 @@ .. _node-pkfactory: -================================== -Generate Custom Values for ``_id`` -================================== +============================== +Generate Custom Values for _id +============================== .. meta:: :description: Learn how to use the MongoDB Node.js Driver to generate custom _id values with a primary key factory during insert operations. diff --git a/source/crud/query.txt b/source/crud/query.txt new file mode 100644 index 000000000..c21336f17 --- /dev/null +++ b/source/crud/query.txt @@ -0,0 +1,38 @@ +.. _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 + +- :ref:`node-find` +- :ref:`node-specify-documents-to-return` +- :ref:`node-project` +- :ref:`node-count` +- :ref:`node-distinct` +- :ref:`node-cursor` +- :ref:`node-geospatial` \ No newline at end of file diff --git a/source/usage-examples/count.txt b/source/crud/query/count.txt similarity index 60% rename from source/usage-examples/count.txt rename to source/crud/query/count.txt index d995917fd..f83fe41e1 100644 --- a/source/usage-examples/count.txt +++ b/source/crud/query/count.txt @@ -1,14 +1,30 @@ .. _node-usage-count: +.. _node-count: =============== Count Documents =============== -.. meta:: - :description: Learn how to count documents in a collection by using the MongoDB Node.js Driver, with methods for both estimated and accurate counts. +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol -The Node.js driver provides two methods for counting documents in a -collection: +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example, node.js, count documents + :description: Learn how to count documents in a collection using the {+driver-long+}. + +Overview +-------- + +In this guide, you can learn how to count the number of documents in your +MongoDB collections. The {+driver-short+} provides two methods for counting +documents in a collection: - `collection.countDocuments() <{+api+}/classes/Collection.html#countDocuments>`__ returns the number of documents in the collection that match the specified query. If you specify an empty @@ -26,7 +42,7 @@ provides an **accurate** count of the number of documents and supports specifying a filter. Choose the appropriate method for your workload. To specify which documents you wish to count, ``countDocuments()`` -accepts a :doc:`query ` parameter. +accepts a :ref:`query ` parameter. ``countDocuments()`` counts the documents that match the specified query. ``countDocuments()`` and ``estimatedDocumentCount()`` support optional @@ -43,43 +59,39 @@ documentation for each method for more information. .. code-block:: javascript - collection.countDocuments({}, { hint: "_id_" }); + collection.countDocuments({}).hint("_id"); + +countDocuments() Example: Full File +----------------------------------- -Example -------- +.. include:: /includes/crud/example-intro.rst + +.. include:: /includes/crud/example-identical-code.rst The following example estimates the number of documents in the ``movies`` collection in the ``sample_mflix`` database, and then returns an accurate count of the number of documents in the ``movies`` -collection with ``Canada`` in the ``countries`` field. - -.. include:: /includes/connect-guide-note.rst - -.. tabs:: - - .. tab:: JavaScript - :tabid: javascript +collection with ``Canada`` in the ``countries`` field: - .. literalinclude:: /code-snippets/usage-examples/count.js - :language: javascript - :linenos: +.. literalinclude:: /code-snippets/usage-examples/count.js + :language: javascript + :linenos: - .. tab:: TypeScript - :tabid: typescript - - .. literalinclude:: /code-snippets/usage-examples/count.js - :language: javascript - :linenos: - -.. note:: Identical Code Snippets - - The JavaScript and TypeScript code snippets above are identical. There are no - TypeScript specific features of the driver relevant to this use case. - -Running the preceding sample code, you see the following output: +Running the preceding sample code results in the following output: .. code-block:: none :copyable: false Estimated number of documents in the movies collection: 23541 Number of movies from Canada: 1349 + +API Documentation +----------------- + +To learn more about any of the types or methods discussed in this guide, see the +following API documentation: + +- `MongoClient <{+api+}/classes/MongoClient.html>`__ +- `Db <{+api+}/classes/Db.html>`__ +- `Collection <{+api+}/classes/Collection.html>`__ +- `countDocuments() <{+api+}/classes/Collection.html#countDocuments>`__ \ No newline at end of file diff --git a/source/fundamentals/crud/read-operations/cursor.txt b/source/crud/query/cursor.txt similarity index 97% rename from source/fundamentals/crud/read-operations/cursor.txt rename to source/crud/query/cursor.txt index d3360c592..2abaaa62b 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 @@ -39,8 +40,8 @@ The following functions directly return cursors: - ``Db.listCollections()`` -Other methods such as :doc:`Collection.findOne() ` -and :doc:`Collection.watch() ` use +Other methods such as :ref:`Collection.findOne() ` +and :doc:`Collection.watch() ` use cursors internally, and return the results of the operations instead of a cursor. diff --git a/source/fundamentals/crud/read-operations/distinct.txt b/source/crud/query/distinct.txt similarity index 78% rename from source/fundamentals/crud/read-operations/distinct.txt rename to source/crud/query/distinct.txt index 6280fdb4d..99300a878 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 @@ -119,7 +120,8 @@ You can specify the collation to the ``distinct()`` method by defining a ``collation`` field as an ``options`` parameter. This field allows you to set regional rules for string ordering and comparisons. -See :ref:`node-fundamentals-collations` for instructions on applying collations. +See the :ref:`node-collations` section of the :ref:`node-configure` guide for +instructions on applying collations. .. note:: @@ -161,15 +163,47 @@ with unaccented first letters: [ "Borgatti's", "Samba Kitchen", "Tanoreen", "Via Carota", "White Bear", "Äpfel" ] -Additional Information ----------------------- +.. _node-usage-distinct: -For a runnable example of retrieving distinct values, see :ref:`node-usage-distinct`. +distinct() Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -API Documentation -~~~~~~~~~~~~~~~~~ +.. include:: /includes/crud/example-intro.rst + +The following snippet retrieves a list of distinct values for the ``year`` +document field from the ``movies`` collection. It uses a query document to +match movies that include ``"Barbara Streisand"`` in the ``director`` array. + +.. tabs:: + + .. tab:: JavaScript + :tabid: javascript + + .. literalinclude:: /code-snippets/usage-examples/distinct.js + :language: javascript + :linenos: + + .. tab:: TypeScript + :tabid: typescript -To learn more about the ``distinct()`` method and its parameters, you can visit the -`API documentation <{+api+}/classes/Collection.html#distinct>`__. + .. literalinclude:: /code-snippets/usage-examples/distinct.ts + :language: typescript + :linenos: + +Running the preceding example, results in the following output: + +.. code-block:: json + :copyable: false + + [ 1983, 1991, 1996 ] + +API Documentation +----------------- +To learn more about any of the types or methods discussed in this guide, see the +following API documentation: +- `MongoClient <{+api+}/classes/MongoClient.html>`__ +- `Db <{+api+}/classes/Db.html>`__ +- `Collection <{+api+}/classes/Collection.html>`__ +- `distinct() <{+api+}/classes/Collection.html#distinct>`__. \ No newline at end of file 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 92% rename from source/fundamentals/crud/read-operations/project.txt rename to source/crud/query/project.txt index 1f23bbc39..d63c8a089 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 @@ -66,8 +67,8 @@ field of each document: :emphasize-lines: 2 // return only* the name field - const projection = { name: 1 }; - const cursor = myColl.find().project(projection); + const projectFields = { name: 1 }; + const cursor = myColl.find().project(projectFields); for await (const doc of cursor) { console.dir(doc); } @@ -103,8 +104,8 @@ returned documents. :emphasize-lines: 2 // return only the name field - const projection = { _id: 0, name: 1 }; - const cursor = myColl.find().project(projection); + const projectFields = { _id: 0, name: 1 }; + const cursor = myColl.find().project(projectFields); for await (const doc of cursor) { console.dir(doc); } @@ -132,8 +133,8 @@ order in which they are returned. .. code-block:: javascript - const projection = { _id: 0, rating: 1, name: 1 }; - const cursor = myColl.find().project(projection); + const projectFields = { _id: 0, rating: 1, name: 1 }; + const cursor = myColl.find().project(projectFields); for await (const doc of cursor) { console.dir(doc); } @@ -151,3 +152,5 @@ the following results: For more projection examples, see the :manual:`MongoDB Manual page on Project Fields to Return from Query `. + +.. include:: /includes/crud/chain-cursor-methods.rst 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..5eb84aafd 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 @@ -12,7 +13,7 @@ Specify a Query .. contents:: On this page :local: :backlinks: none - :depth: 1 + :depth: 2 :class: singlecol Overview diff --git a/source/fundamentals/crud/read-operations/retrieve.txt b/source/crud/query/retrieve.txt similarity index 68% rename from source/fundamentals/crud/read-operations/retrieve.txt rename to source/crud/query/retrieve.txt index 59cfcf8c6..d5f8a22eb 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 @@ -15,7 +16,7 @@ Retrieve Data .. contents:: On this page :local: :backlinks: none - :depth: 1 + :depth: 2 :class: singlecol .. _nodejs-driver-retrieve-data-overview: @@ -41,10 +42,8 @@ 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` +- :ref:`node-specify-documents-to-return` +- :ref:`node-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 @@ -64,8 +63,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 @@ -90,18 +89,16 @@ see the :ref:`node-fundamentals-query-document` guide. 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 + You can chain cursor methods to 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 + specify a projection while performing a find operation that receives an empty query parameter: .. code-block:: javascript - const options = { - projection: { _id: 0, field1: 1 }, - }; + const projectFields = { _id: 0, field1: 1 }; - const findResult = await myColl.findOne({}, options); + const findResult = await myColl.findOne().project(projectFields); For more information about projecting document fields, see the :ref:`node-fundamentals-project` guide. @@ -143,14 +140,105 @@ a ``null`` value if there are no matches. ... ] -Additional Information -~~~~~~~~~~~~~~~~~~~~~~ +.. _node-usage-findone: + +findOne() Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. include:: /includes/crud/example-intro.rst + +The following full file example finds a single document from the ``movies`` +collection. It uses the following parameters: + +- **Filter** that matches documents in which the ``title`` value is ``'The + Room'``. + +- **Sort** that organizes matched documents in descending order by + rating, so if our query matches multiple documents the returned + document will be the document with the highest rating. + +- **Projection** that explicitly excludes the ``_id`` field from + returned documents and explicitly includes only the ``title`` and + ``imdb`` object (and its embedded fields). + +.. _node-driver-findone-usage-example-code-snippet: + +.. tabs:: + + .. tab:: JavaScript + :tabid: javascript + + .. literalinclude:: /code-snippets/usage-examples/findOne.js + :language: javascript + + .. tab:: TypeScript + :tabid: typescript + + .. literalinclude:: /code-snippets/usage-examples/findOne.ts + :language: typescript + + +Running the preceding example results in the following output: + +.. code-block:: javascript + :copyable: false -For runnable code examples that demonstrate find operations, see the following -usage examples: + { title: 'The Room', imdb: { rating: 3.5, votes: 25673, id: 368226 } } -- :ref:`node-usage-findone` -- :ref:`node-usage-find` +.. _node-usage-find: + +find() Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. include:: /includes/crud/example-intro.rst + +The following full file example finds documents from the ``movies`` collection. It +uses the following parameters: + +- **Filter** that matches documents in which the ``runtime`` value is less than 15 + minutes. + +- **Sort** that organizes returned documents in ascending order by + title (alphabetical order in which "A" comes before "Z" and "1" before + "9"). + +- **Projection** that explicitly excludes the ``_id`` field from + returned documents and explicitly includes only the ``title`` and + ``imdb`` object (and its embedded fields). + +.. _node-driver-find-usage-example-code-snippet: + +.. tabs:: + + .. tab:: JavaScript + :tabid: javascript + + .. literalinclude:: /code-snippets/usage-examples/find.js + :language: javascript + :linenos: + + .. tab:: TypeScript + :tabid: typescript + + .. literalinclude:: /code-snippets/usage-examples/find.ts + :language: typescript + :linenos: + +Running the preceding example results in the following output: + +.. code-block:: javascript + :copyable: false + + { title: '10 Minutes', imdb: { rating: 7.9, votes: 743, id: 339976 } } + { title: '3x3', imdb: { rating: 6.9, votes: 206, id: 1654725 } } + { title: '7:35 in the Morning', imdb: { rating: 7.3, votes: 1555, id: 406501 } } + { title: '8', imdb: { rating: 7.8, votes: 883, id: 1592502 } } + ... + +.. include:: /includes/crud/chain-cursor-methods.rst + +Additional Information +~~~~~~~~~~~~~~~~~~~~~~ For more information about the ``findOne()`` and ``find()`` methods, see the following Server manual documentation: @@ -233,8 +321,8 @@ data whenever write operations are executed on the collection. Additional Information ~~~~~~~~~~~~~~~~~~~~~~ -For a runnable example of the ``watch()`` method, see the -:ref:`Watch for Changes ` usage example. +For a runnable example of the ``watch()`` method, see the :ref:`examples +` section in the :ref:`node-change-streams` guide. .. _node-retrieve-instruqt-lab: 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..b4cc4538b --- /dev/null +++ b/source/crud/query/specify-documents-to-return.txt @@ -0,0 +1,278 @@ +.. _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: + +- ``sort()``: Specifies the sort order for the returned documents. +- ``limit()``: Specifies the maximum number of documents to return from a query. +- ``skip()``: Specifies the number of documents to skip before returning query results. + +Sample Data for Examples +~~~~~~~~~~~~~~~~~~~~~~~~ + +To run the examples in this guide, use the following code snippet to insert documents +that describe books into the ``myDB.books`` collection: + +.. code-block:: javascript + + const myDB = client.db("myDB"); + const myColl = myDB.collection("books"); + + await myColl.insertMany([ + { "_id": 1, "name": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 }, + { "_id": 2, "name": "Les Misérables", "author": "Hugo", "length": 1462 }, + { "_id": 3, "name": "Atlas Shrugged", "author": "Rand", "length": 1088 }, + { "_id": 4, "name": "Infinite Jest", "author": "Wallace", "length": 1104 }, + { "_id": 5, "name": "Cryptonomicon", "author": "Stephenson", "length": 918 }, + { "_id": 6, "name": "A Dance With Dragons", "author": "Martin", "length": 1104 }, + ]); + +.. include:: /includes/crud/chain-cursor-methods.rst + +.. include:: /includes/access-cursor-note.rst + +.. _node-fundamentals-sort: + +Sort +---- + +Use the ``sort()`` method to change the order in which read operations return +documents. This method tells MongoDB to order returned documents by the +values of one or more fields in a certain direction. To sort returned +documents by a field in ascending (lowest first) order, use a value of +``1``. To sort in descending (greatest first) order instead, use ``-1``. +If you do not specify a sort, MongoDB does not guarantee the order of +query results. + +The following example passes the sort document to a read operation to ensure that the +operation returns books with longer lengths before books with shorter +lengths: + +.. code-block:: javascript + :emphasize-lines: 4 + + // define an empty query document + const query = {}; + // sort in descending (-1) order by length + const sortFields = { length: -1 }; + const cursor = myColl.find(query).sort(sortFields); + for await (const doc of cursor) { + console.dir(doc); + } + +In this case, the number ``-1`` tells the read operation to sort the +books in descending order by length. ``find()`` returns the following +documents when this sort is used with an empty query: + +.. code-block:: json + :copyable: false + + { "_id": 2, "title": "Les Misérables", "author": "Hugo", "length": 1462 } + { "_id": 4, "title": "Infinite Jest", "author": "Wallace", "length": 1104 } + { "_id": 6, "title": "A Dance with Dragons", "author": "Martin", "length": 1104 } + { "_id": 3, "title": "Atlas Shrugged", "author": "Rand", "length": 1088 } + { "_id": 5, "title": "Cryptonomicon", "author": "Stephenson", "length": 918 } + { "_id": 1, "title": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 } + +Sometimes, the order of two or more documents is ambiguous using a specified sort. In the +preceding example, the documents that have ``title`` values of ``"A Dance with Dragons"`` and +``"Infinite Jest"`` both have a ``length`` of ``1104``, so the order in which they are +returned is not guaranteed. To resolve ties in your sorted results in a repeatable way, +add more fields to the sort document: + +.. code-block:: javascript + :emphasize-lines: 4 + + // define an empty query document + const query = {}; + // sort in ascending (1) order by length + const sortFields = { length: 1, author: 1 }; + const cursor = myColl.find(query).sort(sortFields); + for await (const doc of cursor) { + console.dir(doc); + } + +With the addition of the ``author`` field to the sort document, the read operation sorts +matching documents first by ``length`` then, if there is a tie, by ``author``. Matched +document fields are compared in the same order as fields are specified in the sort +document. ``find()`` returns the following ordering of documents when this sort is used on +the documents matching the query: + +.. code-block:: json + :copyable: false + + { "_id": 1, "title": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 } + { "_id": 5, "title": "Cryptonomicon", "author": "Stephenson", "length": 918 } + { "_id": 3, "title": "Atlas Shrugged", "author": "Rand", "length": 1088 } + { "_id": 6, "title": "A Dance with Dragons", "author": "Martin", "length": 1104 } + { "_id": 4, "title": "Infinite Jest", "author": "Wallace", "length": 1104 } + { "_id": 2, "title": "Les Misérables", "author": "Hugo", "length": 1462 } + +.. _node-fundamentals-limit: + +Limit +----- + +Use the ``limit()`` method to cap the number of documents that can be returned from a read +operation. This method specifies the maximum number of documents that the operation can +return, but the operation can return a smaller number of documents if there are not enough +documents present to reach the limit. If ``limit()`` is used with the :ref:`skip() +` method, the skip applies first and the limit only applies to the +documents left over after the skip. + +This example performs the following actions: + +- Uses an empty query filter to match all documents in the collection +- Calls the ``sort()`` method to apply a descending sort on the ``length`` field to the results +- Calls the ``limit()`` method to return only the first ``3`` results + +.. code-block:: javascript + :emphasize-lines: 5 + + // define an empty query document + const query = {}; + // sort in descending (-1) order by length + const sortFields = { length: -1 }; + const limitNum = 3; + const cursor = myColl.find(query).sort(sortFields).limit(limitNum); + for await (const doc of cursor) { + console.dir(doc); + } + +The code example above outputs the following three documents, sorted by +length: + +.. code-block:: json + :copyable: false + + { "_id": 2, "title": "Les Misérables", "author": "Hugo", "length": 1462 } + { "_id": 6, "title": "A Dance With Dragons", "author": "Martin", "length": 1104 } + { "_id": 4, "title": "Infinite Jest", "author": "Wallace", "length": 1104 } + +.. note:: + + The order in which you call ``limit()`` and ``sort()`` does not matter because the + driver reorders the calls to apply the sort first. The following two calls are + equivalent: + + .. code-block:: javascript + + myColl.find(query).sort({ length: -1 }).limit(3); + myColl.find(query).limit(3).sort({ length: -1 }); + +.. _node-fundamentals-skip: + +Skip +---- + +Use the ``skip()`` method to omit documents from the beginning of the read operation +results. You can combine ``skip()`` with +:ref:`sort() ` to omit the top +(for descending order) or bottom (for ascending order) results for a +given query. Since the :manual:`order of documents returned +` is not guaranteed in +the absence of a sort, using ``skip()`` without using ``sort()`` omits +arbitrary documents. + +If the value of ``skip()`` exceeds the number of matched documents for +a query, then that query returns no documents. + +This example queries the collection for the books with the fifth and sixth highest lengths +by performing the following actions: + +- Uses an empty query filter to match all documents in the collection +- Calls the ``sort()`` method to apply a descending sort to the ``length`` field, which returns longer books before shorter books +- Calls the ``skip()`` method to omit the first four matching documents from the result + +.. code-block:: javascript + + // define an empty query document + const query = {}; + const sortFields = { length: -1 }; + const skipNum = 4; + const cursor = myColl.find(query).sort(sortFields).skip(skipNum); + for await (const doc of cursor) { + console.dir(doc); + } + +Since the query skips the first four matching documents, the preceding code snippet prints +the fifth and sixth highest length documents: + +.. code-block:: json + :copyable: false + + { "_id": 5, "title": "Cryptonomicon", "author": "Stephenson", "length": 918 } + { "_id": 1, "title": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 } + +Combine Limit, Sort, and Skip +----------------------------- + +You can combine the ``limit``, ``sort``, and ``skip`` options in a single +operation. This allows you to set a maximum number of sorted documents to +return, skipping a specified number of documents before returning. + +The following example returns documents with the ``length`` value of +``"1104"``. The results are sorted in alphabetical order, skipping the first +document and includes only the first result: + +.. io-code-block:: + + .. input:: + :language: javascript + + const query = {length: "1104"}; + + const cursor = myColl.find(query).sort({ title: 1 }).skip(1).limit(1); + + for await (const doc of cursor) { + console.dir(doc); + } + + .. output:: + :language: json + :visible: false + + { "_id": 4, "title": "Infinite Jest", "author": "Wallace", "length": 1104 } + +.. note:: + + The order in which you call these methods doesn't change the documents + that are returned. + +Additional Information +---------------------- + +For more information about specifying a query, see :ref:`node-query`. + +For more information about retrieving documents, see :ref:`node-fundamentals-retrieve-data`. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods discussed in this +guide, see the following API documentation: + +- `find() <{+api+}/classes/Collection.html#find>`__ +- `limit() <{+api+}/classes/FindCursor.html#limit>`__ +- `sort() <{+api+}/classes/FindCursor.html#sort>`__ +- `skip() <{+api+}/classes/FindCursor.html#skip>`__ \ 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/transactions.txt b/source/crud/transactions.txt similarity index 94% rename from source/fundamentals/transactions.txt rename to source/crud/transactions.txt index 41e3c9214..4a82050d4 100644 --- a/source/fundamentals/transactions.txt +++ b/source/crud/transactions.txt @@ -1,4 +1,5 @@ .. _nodejs-transactions: +.. _node-transactions: ============ Transactions @@ -18,6 +19,12 @@ Transactions :depth: 2 :class: singlecol +.. toctree:: + :caption: Transaction Usage Examples + + Convenient Transaction API + Core API + Overview -------- @@ -47,18 +54,6 @@ ACID transactions `. Operations ` section in the Server manual. -In MongoDB, multi-document transactions run within a **client session**. -A client session is a grouping of related read or write operations that -you want to execute sequentially. We recommend you reuse -your client for multiple sessions and transactions instead of -instantiating a new client each time. - -When combined with ``majority`` read and -write concerns, the driver guarantees causal consistency between the -operations. To learn more, see :manual:`Client Sessions and Causal Consistency Guarantees -` in the -Server manual. - Learn more about how to use the driver to perform multi-document transactions in the following sections of this guide: @@ -66,6 +61,37 @@ transactions in the following sections of this guide: - :ref:`Transaction Options ` - :ref:`Transaction Errors ` +.. _nodejs-causal-consistency: + +Causal Consistency +~~~~~~~~~~~~~~~~~~ + +.. sharedinclude:: dbx/causal-consistency.rst + + .. replacement:: insert-one-method + + ``insertOne()`` + + .. replacement:: update-one-method + + ``updateOne()`` + + .. replacement:: find-one-method + + ``findOne()`` + + .. replacement:: delete-one-method + + ``deleteOne()`` + + .. replacement:: majority-rc + + ``majority`` + + .. replacement:: majority-wc + + ``majority`` + .. _nodejs-transaction-apis: Transaction APIs diff --git a/source/usage-examples/transaction-conv.txt b/source/crud/transactions/transaction-conv.txt similarity index 98% rename from source/usage-examples/transaction-conv.txt rename to source/crud/transactions/transaction-conv.txt index 149f99146..3e918dda3 100644 --- a/source/usage-examples/transaction-conv.txt +++ b/source/crud/transactions/transaction-conv.txt @@ -4,9 +4,14 @@ Use the Convenient Transaction API ================================== +.. facet:: + :name: genre + :values: reference + .. meta:: :description: Perform a transaction using the Convenient Transaction API with the MongoDB Node.js Driver to update data atomically. - + :keywords: modify, customize + .. contents:: On this page :local: :backlinks: none diff --git a/source/usage-examples/transaction-core.txt b/source/crud/transactions/transaction-core.txt similarity index 98% rename from source/usage-examples/transaction-core.txt rename to source/crud/transactions/transaction-core.txt index 0c2545325..bf8d3714e 100644 --- a/source/usage-examples/transaction-core.txt +++ b/source/crud/transactions/transaction-core.txt @@ -4,8 +4,13 @@ Use the Core API ================ +.. facet:: + :name: genre + :values: reference + .. meta:: :description: Use the Core API with the MongoDB Node.js Driver to update multiple documents in a single transaction. + :keywords: modify, customize .. contents:: On this page :local: diff --git a/source/fundamentals/crud/write-operations/upsert.txt b/source/crud/update.txt similarity index 88% rename from source/fundamentals/crud/write-operations/upsert.txt rename to source/crud/update.txt index ad400ded8..8855761d8 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 @@ -15,9 +16,17 @@ Insert or Update in a Single Operation .. contents:: On this page :local: :backlinks: none - :depth: 1 + :depth: 2 :class: singlecol +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Modify Documents + Replace + Update Arrays + Overview -------- @@ -27,9 +36,9 @@ an insert or update operation depends on whether the document exists. In these cases, you can streamline your application logic by using the ``upsert`` option available in the following methods: -- :doc:`updateOne() ` -- :doc:`replaceOne() ` -- :doc:`updateMany() ` +- :ref:`updateOne() ` +- :ref:`replaceOne() ` +- :ref:`updateMany() ` If the query filter passed to these methods does not find any matches and you set the ``upsert`` option to ``true``, MongoDB inserts the update @@ -70,6 +79,8 @@ If a food truck named "Deli Llama" exists, the method call above updates the document in the collection. However, if there are no food trucks named "Deli Llama" in your collection, no changes are made. +.. _node-upsert: + Performing an Upsert -------------------- 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 63% rename from source/fundamentals/crud/write-operations/modify.txt rename to source/crud/update/modify.txt index 06624209d..501c0359d 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 @@ -10,9 +11,16 @@ Modify Documents .. contents:: On this page :local: :backlinks: none - :depth: 1 + :depth: 2 :class: singlecol +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example, node.js, modify data + Overview -------- @@ -29,6 +37,8 @@ The {+driver-short+} provides the following methods to change documents: - ``updateMany()`` - ``replaceOne()`` +To learn how to replace documents, see the :ref:`` guide. + .. tip:: Interactive Lab This page includes a short interactive lab that demonstrates how to @@ -133,99 +143,100 @@ 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 for more information on :manual:`unique indexes `. -.. _node-fundamentals-replaceone: -.. _replacementDocument: +.. _node-usage-updateone: -Replace a Document ------------------- +updateOne() Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -To perform a replacement operation, create a **replacement document** that -consists of the fields and values that you want to use in your -**replace** operation. Replacement documents use the following format: +.. include:: /includes/crud/example-intro.rst -.. code-block:: javascript +This example uses the ``$set`` update operator which specifies +update values for document fields. For more information on update operators, +see the :manual:`MongoDB update operator reference documentation +`. - { - : { - - }, - : { - ... - } - } +The following code is a complete, standalone file that performs an update one +operation: -Replacement documents are the documents that you want to take the place of -existing documents that match the query filters. +.. tabs:: -Example -~~~~~~~ + .. tab:: JavaScript + :tabid: javascript -Consider a document in the ``myDB.items`` collection with fields -describing an item for sale, its price, and the quantity available: + .. literalinclude:: /code-snippets/usage-examples/updateOne.js + :language: javascript + :linenos: -.. code-block:: javascript + .. tab:: TypeScript + :tabid: typescript - { - _id: 501, - item: "3-wick beeswax candle", - price: 18.99, - quantity: 10, - } + .. literalinclude:: /code-snippets/usage-examples/updateOne.ts + :language: typescript + :linenos: -Suppose you wanted to replace this document with one that contains a -description for an entirely different item. Your replacement operation might -resemble the following: +Running the preceding example results in the following output: -.. code-block:: javascript +.. code-block:: none + :copyable: false - const myDB = client.db("myDB"); - const myColl = myDB.collection("items"); + 1 document(s) matched the filter, updated 1 document(s) - const filter = { _id: 501 }; +.. _node-usage-updatemany: - // replace the matched document with the replacement document - const replacementDocument = { - item: "Vintage silver flatware set", - price: 79.15, - quantity: 1, - }; - const result = await myColl.replaceOne(filter, replacementDocument); +updateMany() Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The replaced document contains the contents of the replacement document -and the immutable ``_id`` field as follows: +.. include:: /includes/crud/example-intro.rst -.. code-block:: javascript - :copyable: false +The following code is a complete, standalone file that performs an update many +operation: - { - _id: 501, - item: "Vintage silver flatware set", - price: 79.15, - quantity: 1, - } +.. tabs:: -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 -attempts to perform the replacement, but if no documents are matched, it -inserts a new document with the specified fields and values. + .. tab:: JavaScript + :tabid: javascript -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 -for more information on :manual:`unique indexes `. + .. literalinclude:: /code-snippets/usage-examples/updateMany.js + :language: javascript + :linenos: + + .. tab:: TypeScript + :tabid: typescript + + .. literalinclude:: /code-snippets/usage-examples/updateMany.ts + :language: typescript + :linenos: + +Running the preceding example, you see an output like the following: + +.. code-block:: none + :copyable: false + + Updated 477 documents .. _node-update-instruqt-lab: .. instruqt:: /mongodb-docs/tracks/update-node?token=em_FEr9KfMh4WQ0VosU :title: updateMany() Lesson - :drawer: \ No newline at end of file + :drawer: + +API Documentation +----------------- + +To learn more about any of the types or methods discussed in this guide, see the +following API documentation: + +- `MongoClient <{+api+}/classes/MongoClient.html>`__ +- `Db <{+api+}/classes/Db.html>`__ +- `Collection <{+api+}/classes/Collection.html>`__ +- `updateOne() <{+api+}/classes/Collection.html#updateOne>`__ +- `updateMany() <{+api+}/classes/Collection.html#updateMany>`__ \ No newline at end of file diff --git a/source/crud/update/replace.txt b/source/crud/update/replace.txt new file mode 100644 index 000000000..43b7b7ca7 --- /dev/null +++ b/source/crud/update/replace.txt @@ -0,0 +1,169 @@ +.. _node-replace: + +================= +Replace Documents +================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. 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. + +.. _node-fundamentals-replaceone: +.. _replacementDocument: + +Replace a Document +------------------ + +To perform a replacement operation, create a **replacement document** that +consists of the fields and values that you want to use in your +**replace** operation. Replacement documents use the following format: + +.. code-block:: javascript + + { + : { + + }, + : { + ... + } + } + +Replacement documents are the documents that you want to take the place of +existing documents that match the query filters. + +You can specify more options, such as ``upsert``, using the +optional ``options`` parameter. If you set the ``upsert`` option field to +``true`` the method inserts a new document if no document matches the query. + +The ``replaceOne()`` method throws an exception if an error occurs +during execution. For example, if you specify a value that violates a +unique index rule, ``replaceOne()`` throws a ``duplicate key error``. + +.. note:: + + If your application requires the document after updating, + use the `collection.findOneAndReplace() <{+api+}/classes/Collection.html#findOneAndReplace>`__ + method which has a similar interface to ``replaceOne()``. + You can configure ``findOneAndReplace()`` to return either the + original matched document or the replacement document. + +Example +~~~~~~~ + +Consider a document in the ``myDB.items`` collection with fields +describing an item for sale, its price, and the quantity available: + +.. code-block:: javascript + + { + _id: 501, + item: "3-wick beeswax candle", + price: 18.99, + quantity: 10, + } + +Suppose you wanted to replace this document with one that contains a +description for an entirely different item. Your replacement operation might +resemble the following: + +.. code-block:: javascript + + const myDB = client.db("myDB"); + const myColl = myDB.collection("items"); + + const filter = { _id: 501 }; + + // replace the matched document with the replacement document + const replacementDocument = { + item: "Vintage silver flatware set", + price: 79.15, + quantity: 1, + }; + const result = await myColl.replaceOne(filter, replacementDocument); + +The replaced document contains the contents of the replacement document +and the immutable ``_id`` field as follows: + +.. code-block:: javascript + :copyable: false + + { + _id: 501, + item: "Vintage silver flatware set", + price: 79.15, + quantity: 1, + } + +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 :ref:`upsert ` which +attempts to perform the replacement, but if no documents are matched, it +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 +for more information on :manual:`unique indexes `. + +.. _node-usage-replaceone: + +replaceOne() Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. include:: /includes/crud/example-intro.rst + +The following code is a complete, standalone file that performs a replace one +operation: + +.. tabs:: + + .. tab:: JavaScript + :tabid: javascript + + .. literalinclude:: /code-snippets/usage-examples/replaceOne.js + :language: javascript + :linenos: + + .. tab:: TypeScript + :tabid: typescript + + .. literalinclude:: /code-snippets/usage-examples/replaceOne.ts + :language: typescript + :linenos: + +Running the preceding example results in the following output: + +.. code-block:: none + :copyable: false + + Modified 1 document(s) + +API Documentation +----------------- + +To learn more about any of the types or methods discussed in this guide, see the +following API documentation: + +- `MongoClient <{+api+}/classes/MongoClient.html>`__ +- `Db <{+api+}/classes/Db.html>`__ +- `Collection <{+api+}/classes/Collection.html>`__ +- `replaceOne() <{+api+}/classes/Collection.html#replaceOne>`__ +- `findOneAndReplace() <{+api+}/classes/Collection.html#findOneAndReplace>`__ \ No newline at end of file diff --git a/source/data-formats.txt b/source/data-formats.txt new file mode 100644 index 000000000..a0b28f2a8 --- /dev/null +++ b/source/data-formats.txt @@ -0,0 +1,36 @@ +.. _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 + Extended JSON + 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..28726bc22 --- /dev/null +++ b/source/data-formats/bson.txt @@ -0,0 +1,171 @@ +.. _node-bson-control: +.. _node-bson: + +=================== +Work with BSON Data +=================== + +.. 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 the {+driver-short+}. + +**BSON**, or Binary JSON, is the data format that MongoDB uses to organize +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>`__ diff --git a/source/data-formats/extended-json.txt b/source/data-formats/extended-json.txt new file mode 100644 index 000000000..0f1a93bd0 --- /dev/null +++ b/source/data-formats/extended-json.txt @@ -0,0 +1,219 @@ +.. _node-extended-json: + +============================ +Work with Extended JSON Data +============================ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code examples, bson, relaxed, canonical, legacy + +Overview +-------- + +JSON is a data format that represents the values of objects, arrays, numbers, +strings, booleans, and nulls. The **Extended JSON** format defines a reserved +set of keys prefixed with "``$``" to represent field type information that +directly corresponds to each type in BSON, the format that MongoDB uses to +store data. + +Extended JSON Formats +--------------------- + +MongoDB Extended JSON features different string formats to represent BSON data. +Each of the different formats conform to the JSON RFC +and meet specific use cases. The **Extended** format, also known as the +**Canonical** format, features specific representations for every BSON type +for bidirectional conversion without loss of information. The **Relaxed Mode** +format is more concise and closer to ordinary JSON, but does not represent +all the type information such as the specific bit width of numeric fields. + +See the following table to see a description of each format: + +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + :widths: 10 40 + + * - Name + - Description + + * - **Extended** + - | Also known as the *Canonical* format, this JSON representation avoids loss of + BSON type information. + | This format prioritizes type preservation at the loss of human-readability and + interoperability with older formats. + + * - **Relaxed Mode** + - | JSON representation that describes BSON documents with some type information loss. + | This format prioritizes human-readability and interoperability at the loss of + certain type information. + +To learn more about JSON, BSON, and Extended JSON, see +`our article about JSON and BSON `__ +and :manual:`Extended JSON ` in the {+mdb-server+} manual. + +.. _extended_json_example_section: + +Extended JSON Examples +~~~~~~~~~~~~~~~~~~~~~~ + +The following examples show a document containing an ObjectId, date, and long +number field represented in the Extended JSON format. Click the tab that +corresponds to the format of the example you want to see: + +.. tabs:: + + .. tab:: Extended + :tabid: extended-format + + .. code-block:: json + + { + "_id": { "$oid": "573a1391f29313caabcd9637" }, + "createdAt": { "$date": { "$numberLong": "1601499609" }}, + "numViews": { "$numberLong": "36520312" } + } + + .. tab:: Relaxed Mode + :tabid: relaxed-mode-format + + .. code-block:: json + + { + "_id": { "$oid": "573a1391f29313caabcd9637" }, + "createdAt": { "$date": "2020-09-30T18:22:51.648Z" }, + "numViews": 36520312 + } + +Write Extended JSON +------------------- + +You can write an Extended JSON string from a BSON document object by using the +``EJSON.stringify()`` method. + +The following example outputs an Extended JSON string in the Relaxed format: + +.. io-code-block:: + + .. input:: + :language: js + + import { Code, BSON } from 'mongodb'; + const EJSON = BSON.EJSON; + + const doc = { + foo: [1, 2], + bar: { hello: "world" }, + code: new Code("function x() { return 1; }", {}), + date: new Date(2024, 6, 20, 10, 30, 0), + }; + + const ejsonStr = EJSON.stringify(doc); + console.log(ejsonStr); + + .. output:: + :language: none + :visible: false + + {"foo":[1,2],"bar":{"hello":"world"},"code":{"$code":"function x() { return 1; }","$scope":{}},"date":{"$date":"2024-07-20T14:30:00Z"}} + +By default, the ``stringify()`` method returns the Extended JSON string in the +Relaxed format. To specify the Canonical format, set the ``relaxed`` +option to ``false``. + +The following example shows how to output Extended JSON in the Canonical format: + +.. io-code-block:: + + .. input:: + :language: js + + import { Code, BSON } from 'mongodb'; + const EJSON = BSON.EJSON; + + const doc = { + foo: [1, 2], + bar: { hello: "world" }, + code: new Code("function x() { return 1; }", {}), + date: new Date(2024, 6, 20, 10, 30, 0), + }; + + const ejsonStr = EJSON.stringify(doc, { relaxed: false }); + print(ejsonStr) + + .. output:: + :language: none + :visible: false + + {"foo":[{"$numberInt":"1"},{"$numberInt":"2"}],"bar":{"hello":"world"},"code":{"$code":"function x() { return 1; }","$scope":{}},"date":{"$date":{"$numberLong":"1721485800000"}}} + +Read Extended JSON +------------------ + +You can read an Extended JSON string into the JavaScript value or object described +by the string by using the ``EJSON.parse()`` method. + +The following example shows how you can read an Extended JSON string into a +JavaScript value or object by using the ``parse()`` method: + +.. The back ticks on ejsonStr in the below code example causes the orange +.. highlighting in this file, but the page still renders correctly. + +.. io-code-block:: + + .. input:: + :language: javascript + + import { BSON } from 'mongodb'; + const EJSON = BSON.EJSON; + + const ejsonStr = `{ + "foo": [ + { "$numberInt": "1" }, + { "$numberInt": "2" } + ], + "bar": { "hello": "world" }, + "code": { + "$code": "function x() { return 1; }", + "$scope": {} + }, + "bin": { "$binary": { "base64": "AQIDBA==", "subType": "00" } } + }`; + + const doc = EJSON.parse(ejsonStr); + console.log(doc); + + .. output:: + :language: none + :visible: false + + { + foo: [ 1, 2 ], + bar: { hello: 'world' }, + code: new Code('function x() { return 1; }', {}), + bin: Binary.createFromBase64('AQIDBA==', 0) + } + +.. note:: + + The driver parses the ``$uuid`` Extended JSON type from a string to a + ``BsonBinary`` object of binary subtype 4. For more information about ``$uuid`` field + parsing, see the + :spec:`Special Rules for Parsing $uuid Fields ` + section in the extended JSON specification. + +API Documentation +----------------- + +To learn more about any of the methods or types discussed in this +guide, see the `EJSON `__ API documentation. 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/databases-collections.txt b/source/databases-collections.txt new file mode 100644 index 000000000..a1ab63e97 --- /dev/null +++ b/source/databases-collections.txt @@ -0,0 +1,193 @@ +.. _node-databases-collections: + +========================= +Databases and Collections +========================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: table, row, organize, storage, code example + +Overview +-------- + +In this guide, you can learn how to interact with MongoDB databases and +collections by using the {+driver-short+}. + +MongoDB organizes data into a hierarchy of the following levels: + +- **Databases**: Top-level data structures in a MongoDB deployment that store collections. +- **Collections**: Groups of MongoDB documents. They are analogous to tables in relational databases. +- **Documents**: Units that store literal data such as strings, numbers, dates, and other embedded documents. + For more information about document field types and structure, see the + :manual:`Documents ` entry in the {+mdb-server+} manual. + +Access a Database +----------------- + +You can access a database by calling the ``db()`` method on a +``MongoClient`` instance. + +The following example accesses a database named ``"test_database"``: + +.. literalinclude:: /includes/databases-collections.js + :start-after: start-access-database + :end-before: end-access-database + :language: javascript + :copyable: + :dedent: + +Access a Collection +------------------- + +You can access a collection by calling the ``collection()`` method on a ``Db`` +instance. + +The following example accesses a collection named ``"test_collection"``: + +.. literalinclude:: /includes/databases-collections.js + :start-after: start-access-collection + :end-before: end-access-collection + :language: javascript + :copyable: + :dedent: + +.. tip:: + + If the provided collection name does not already exist in the database, + MongoDB implicitly creates the collection when you first insert data + into it. + +Create a Collection +------------------- + +To explicitly create a collection, call the ``createCollection()`` method on +a ``Db`` instance. + +The following example creates a collection named ``"example_collection"``: + +.. literalinclude:: /includes/databases-collections.js + :start-after: start-create-collection + :end-before: end-create-collection + :language: javascript + :copyable: + :dedent: + +You can specify collection options, such as maximum size and document +validation rules, by passing a ``CreateCollectionOptions`` instance to the +``createCollection()`` method. For a full list of +optional parameters, see the :manual:`create command ` +entry in the {+mdb-server+} manual. + +Get a List of Collections +------------------------- + +You can query for a list of collections in a database by calling the +``listCollections()`` method on a ``Db`` instance. + +The following example lists all collections in a database: + +.. io-code-block:: + :copyable: + + .. input:: /includes/databases-collections.js + :language: javascript + :start-after: start-find-collections + :end-before: end-find-collections + :dedent: + + .. output:: + :language: console + :visible: false + + { + name: 'example_collection', + type: 'collection', + options: {}, + info: { + readOnly: false, + uuid: new UUID('...') + }, + idIndex: { v: 2, key: { _id: 1 }, name: '_id_' } + } + { + name: 'test_collection', + type: 'collection', + options: {}, + info: { + readOnly: false, + uuid: new UUID('...') + }, + idIndex: { v: 2, key: { _id: 1 }, name: '_id_' } + } + +To query for only the names of the collections in the database, pass +the ``nameOnly`` option to the ``listCollections()`` method and set its +value to ``true``, as shown in the following code: + +.. io-code-block:: + :copyable: + + .. input:: /includes/databases-collections.js + :language: javascript + :start-after: start-find-collection-names + :end-before: end-find-collection-names + :dedent: + + .. output:: + :language: console + :visible: false + + { name: 'example_collection', type: 'collection' } + { name: 'test_collection', type: 'collection' } + +.. tip:: + + For more information about iterating over a cursor, see the :ref:`node-cursor` + guide. + +Delete a Collection +------------------- + +You can delete a collection by calling the ``drop()`` method on a +``Collection`` instance. + +The following example deletes the ``"test_collection"`` collection: + +.. literalinclude:: /includes/databases-collections.js + :start-after: start-delete-collection + :end-before: end-delete-collection + :language: javascript + :copyable: + :dedent: + +.. warning:: Dropping a Collection Deletes All Data in the Collection + + Dropping a collection from your database permanently deletes all + documents and all indexes within that collection. + + Drop a collection only if the data in it is no longer needed. + +API Documentation +----------------- + +To learn more about any of the types or methods discussed in this +guide, see the following API documentation: + +- `MongoClient <{+api+}/classes/MongoClient.html>`__ +- `Db <{+api+}/classes/Db.html>`__ +- `Collection <{+api+}/classes/Collection.html>`__ +- `db() <{+api+}/classes/MongoClient.html#db>`__ +- `collection() <{+api+}/classes/Db.html#collection>`__ +- `createCollection() <{+api+}/classes/Db.html#createCollection>`__ +- `listCollections() <{+api+}/classes/Db.html#listCollections>`__ +- `dropCollection() <{+api+}/classes/Db.html#dropCollection>`__ \ No newline at end of file diff --git a/source/faq.txt b/source/faq.txt deleted file mode 100644 index c472fc187..000000000 --- a/source/faq.txt +++ /dev/null @@ -1,369 +0,0 @@ -.. _node-faq: - -=== -FAQ -=== - -.. meta:: - :description: Find answers to frequently asked questions about the MongoDB Node.js Driver, including connection pooling, timeouts, and handling network behavior. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 1 - :class: singlecol - -This page contains frequently asked questions and their corresponding answers. - -.. tip:: - - If you can't find an answer to your problem on this page, - see the :ref:`node-issues-help` page for next steps and more - resources. - -Why Am I Getting Errors While Connecting to MongoDB? ----------------------------------------------------- - -If you have trouble connecting to a MongoDB deployment, see -the :ref:`Connection Troubleshooting Guide ` -for possible solutions. - -.. _node-faq-connection-pool: - -How Does Connection Pooling Work in the Node Driver? ----------------------------------------------------- - -Every ``MongoClient`` instance has a built-in connection pool for each server -in your MongoDB topology. Connection pools open sockets on demand to -support concurrent requests to MongoDB in your application. - -The maximum size of each connection pool is set by the ``maxPoolSize`` option, which -defaults to ``100``. If the number of in-use connections to a server reaches -the value of ``maxPoolSize``, the next request to that server will wait -until a connection becomes available. - -In addition to the sockets needed to support your application's requests, -each ``MongoClient`` instance opens two more sockets 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`` total 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. - -To support high numbers of concurrent MongoDB requests -within one process, you can increase ``maxPoolSize``. - -Connection pools are rate-limited. 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 driver's ability to reuse existing connections improves due to - rate-limits on connection creation. - -You can set the minimum number of concurrent connections to -each server with the ``minPoolSize`` option, which defaults to ``0``. -The driver initializes the connection pool with this number of sockets. 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. - -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 default configuration for a ``MongoClient`` works for most -applications: - -.. code-block:: js - - const client = new MongoClient(""); - -``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. - -When ``MongoClient.close()`` is called by any request, the driver -closes all idle sockets and closes all sockets that are in -use as they are returned to the pool. Calling ``MongoClient.close()`` -closes only inactive sockets and does not directly terminate -any ongoing operations. The driver closes any in-use sockets only when -the associated operations complete. However, the ``MongoClient.close()`` -method does close existing sessions and transactions, which might indirectly -affect the behavior of ongoing operations and open cursors. - -What Is the Difference Between "connectTimeoutMS", "socketTimeoutMS" and "maxTimeMS"? -------------------------------------------------------------------------------------- - -.. list-table:: - :widths: 22 78 - :header-rows: 1 - - * - Setting - - Description - * - **connectTimeoutMS** - - ``connectTimeoutMS`` is a :ref:`connection option - ` that sets the time, in milliseconds, - for an individual connection from your connection pool to - establish a TCP connection to the {+mdb-server+} before - timing out. To modify the allowed time for - `MongoClient.connect <{+api+}/classes/MongoClient.html#connect>`__ to establish a - connection to a {+mdb-server+}, use the ``serverSelectionTimeoutMS`` option instead. - - **Default:** 30000 - * - **socketTimeoutMS** - - ``socketTimeoutMS`` specifies the amount of time the driver waits - for an inactive socket before closing it. The default value is to - never time out the socket. This option applies only to sockets that - have already been connected. - * - **maxTimeMS** - - `maxTimeMS <{+api+}/classes/FindCursor.html#maxTimeMS>`__ - specifies the maximum amount of time that the server - waits for an operation to complete after it has reached the - server. If an operation runs over the specified time limit, it - returns a timeout error. You can pass ``maxTimeMS`` only to an - individual operation or to a cursor. - -To specify the optional settings for your ``MongoClient``, declare one or -more available settings in the ``options`` object of the constructor as -follows: - -.. code-block:: javascript - - const client = new MongoClient(uri, { - connectTimeoutMS: , - socketTimeoutMS: - }); - -To see all the available settings, see the -`MongoClientOptions <{+api+}/interfaces/MongoClientOptions.html>`__ -API Documentation. - -To specify ``maxTimeMS``, chain the ``maxTimeMS()`` method with a -timeout specification to an operation that returns a ``Cursor``: - -.. code-block:: javascript - - const cursor = myColl.find({}).maxTimeMS(50); - -What Happens to Running Operations if the Client Disconnects? -------------------------------------------------------------- - -Starting in {+mdb-server+} version 4.2, the server terminates -running operations such as aggregations and find operations if the -client disconnects. - -Other operations, such as write operations, continue to run on the -{+mdb-server+} even if the client disconnects. This behavior can cause data -inconsistencies if your application retries the operation after the -client disconnects. - -How Can I Confirm That the Driver Closed Unusable Sockets? ----------------------------------------------------------- - -If you experience unexpected network behavior or if a MongoDB process -fails with an error, you may not receive confirmation that the -driver correctly closed the corresponding socket. - -To make sure that the driver correctly closes the socket in these cases, -set the ``socketTimeoutMS`` option. When a MongoDB process times out, the driver -will close the socket. We recommend that you select a value -for ``socketTimeoutMS`` that is two to three times longer than the -expected duration of the slowest operation that your application executes. - -How Can I Prevent Sockets From Timing Out Before They Become Active? --------------------------------------------------------------------- - -Having a large connection pool does not always reduce reconnection -requests. Consider the following example: - -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. - -One message every 3000 milliseconds is not enough to keep the sockets -active, so several of the sockets will time out after 5000 milliseconds. -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 specify the optional ``maxPoolSize`` setting for your ``MongoClient``, declare -it in the ``options`` object of the constructor as follows: - -.. code-block:: javascript - - const client = new MongoClient(uri, { - maxPoolSize: , - }); - -What Does a Value of "0" Mean for "connectTimeoutMS" and "socketTimeoutMS"? ---------------------------------------------------------------------------- - -If you set the value of ``connectTimeoutMS`` or ``socketTimeoutMS`` to -``0``, your application will use the operating system's default socket -timeout value. - -How Can I Prevent Long-Running Operations From Slowing Down the Server? ------------------------------------------------------------------------ - -You can prevent long-running operations from slowing down the server by -specifying a timeout value. You can chain the ``maxTimeMS()`` method to -an operation that returns a ``Cursor`` to set a timeout on a specific action. - -The following example shows how you can chain the ``maxTimeMS()`` method -to an operation that returns a ``Cursor``: - -.. literalinclude:: /code-snippets/faq/maxTimeMS-example.js - :language: javascript - -.. _node-faq-keepalive: - -What Does the keepAlive Option Do? ----------------------------------- - -The ``keepAlive`` connection option specifies whether to enable -:wikipedia:`Transmission Control Protocol (TCP) keepalives -` on a TCP socket. If you enable keepalives, -the driver checks whether the connection is active by sending periodic pings -to your MongoDB deployment. This functionality only works if your -operating system supports the ``SO_KEEPALIVE`` socket option. - -The ``keepAliveInitialDelay`` option specifies the number of -milliseconds that the driver waits before initiating a keepalive. - -The 5.3 driver version release deprecated these options. Starting in -version 6.0 of the driver, the ``keepAlive`` option is permanently set -to ``true``, and the ``keepAliveInitialDelay`` is set to 300000 -milliseconds (300 seconds). - -.. warning:: - - If your firewall ignores or drops the keepalive messages, you might - not be able to identify dropped connections. - -What Can I Do If I'm Experiencing Unexpected Network Behavior? --------------------------------------------------------------- - -You might experience unexpected network behavior if the firewall between -your application and MongoDB is misconfigured. These firewalls can be -overly aggressive in their removal of connections, which can lead to -unexpected errors. - -Confirm that your firewall exhibits the following behavior: - -- The firewall sends a ``FIN`` packet when closing a connection, - informing the driver that the socket is closed. - -- The firewall allows keepalive messages. - -.. tip:: - - To learn more about keepalive messages, see the :ref:`What Does the - keepAlive Option Do? ` FAQ entry. - -How Can I Prevent a Slow Operation From Delaying Other Operations? ------------------------------------------------------------------- - -When you use the same ``MongoClient`` instance to run multiple MongoDB -operations concurrently, a slow operation can cause delays to other -operations. Slow operations keep a connection to MongoDB occupied, -which can cause other operations to wait until an additional connection -becomes available. - -If you suspect that slow MongoDB operations are causing delays, you -can check the performance of all in-progress operations by using the -following methods: - -- Enable the database profiler on your deployment. To learn more, see - :manual:`Database Profiler ` - in the Server manual. -- Run the ``db.currentOp()`` MongoDB Shell command. To learn more, see the - :manual:`db.currentOp() ` - documentation in the Server manual. -- Enable connection pool monitoring. To learn more, see - :ref:`node-connection-pool-monitoring`. - -After you determine which operations are causing delays, try to improve -the performance of these operations. Read the :website:`Best Practices -Guide for MongoDB Performance ` for possible solutions. - -If you implement performance best practices but still -experience delays, you can modify your connection settings to increase -the size of the connection pool. A connection pool is the group of -connections to the server that the driver maintains at any time. - -To specify the maximum size of a -connection pool, you can set the ``maxPoolSize`` option in the -:ref:`connection options ` for your -``MongoClient`` instance. The default value -of ``maxPoolSize`` is ``100``. If the number of in-use connections to a -server reaches ``maxPoolSize``, the next operation sent to the server -pauses until a connection to the driver becomes available. The following -code sets ``maxPoolSize`` to ``150`` when creating a new ``MongoClient``: - -.. code-block:: js - - const client = new MongoClient(uri, { maxPoolSize: 150 }); - -.. tip:: - - To learn more about connection pooling, see the :ref:`How Does Connection - Pooling Work in the Node Driver? ` FAQ entry. - -How Can I Ensure my Connection String Is Valid for a Replica Set? ------------------------------------------------------------------ - -The connection string passed to the driver must use exact hostnames for -the servers as set in the :manual:`Replica Set Config `. -Given the following configuration settings for your Replica Set, in -order for the Replica Set discovery and :manual:`failover -` to work, the driver must have access -to ``server1``, ``server2``, and ``server3``. - -.. code-block:: JSON - - { - "_id": "testSet", - "version": 1, - "protocolVersion": 1, - "members": [ - { - "_id": 1, - "host": "server1:31000" - }, - { - "_id": 2, - "host": "server2:31001" - }, - { - "_id": 3, - "host": "server3:31002" - } - ] - } - -If you are unable to find the answer to your question here, try our forums and -support channels listed in the :doc:`Issues and Help ` -section. diff --git a/source/fundamentals.txt b/source/fundamentals.txt deleted file mode 100644 index b5ef4e2ab..000000000 --- a/source/fundamentals.txt +++ /dev/null @@ -1,30 +0,0 @@ -============ -Fundamentals -============ - -.. meta:: - :description: Explore tasks using the MongoDB Node.js Driver, including connecting, authenticating, reading, writing, and managing transactions in MongoDB. - -.. default-domain:: mongodb - -.. toctree:: - - Connection - Stable API - Authentication - CRUD Operations - Promises - Aggregation - Transactions - Run a Command - Indexes - Collations - Logging - Monitoring - GridFS - Time Series - TypeScript - BSON Settings - In-Use Encryption - -.. include:: /includes/fundamentals-sections.rst diff --git a/source/fundamentals/authentication.txt b/source/fundamentals/authentication.txt deleted file mode 100644 index 2a6c3ef6f..000000000 --- a/source/fundamentals/authentication.txt +++ /dev/null @@ -1,46 +0,0 @@ -.. _node-authentication-mechanisms: - -============== -Authentication -============== - -.. meta:: - :description: Authenticate using the MongoDB Node.js Driver with various supported authentication mechanisms. - -.. default-domain:: mongodb - -.. toctree:: - - Authentication - Enterprise Authentication - -Overview --------- - -These guides show you how to authenticate to a MongoDB instance using the -Node.js driver. - -The :doc:`Authentication Mechanisms ` guide contains -sample connection code using each authentication mechanism supported in the -MongoDB Community Edition which includes: - -- ``DEFAULT`` -- ``SCRAM-SHA-256`` -- ``SCRAM-SHA-1`` -- ``MONGODB-CR`` -- ``MONGODB-AWS`` -- ``X.509`` - -The :doc:`Enterprise Authentication Mechanisms -` guide contains sample -connection code using authentication mechanisms available only in MongoDB -Enterprise Edition which includes: - -- ``Kerberos (GSSAPI/SSPI)`` -- ``LDAP (PLAIN)`` -- ``MONGODB-OIDC`` - -.. note:: - For instructions on MongoDB driver installation and deployment setup, see - our :guides:`Connect to MongoDB guide `. Select your - MongoDB deployment type and the Node.js client. diff --git a/source/fundamentals/authentication/mechanisms.txt b/source/fundamentals/authentication/mechanisms.txt deleted file mode 100644 index 5ba01f5f1..000000000 --- a/source/fundamentals/authentication/mechanisms.txt +++ /dev/null @@ -1,369 +0,0 @@ -.. _node-community-authentication-mechanisms: - -========================= -Authentication Mechanisms -========================= - -.. meta:: - :description: Explore sample code for connecting to MongoDB using various authentication mechanisms with the MongoDB Node.js Driver, including `SCRAM-SHA-256`, `SCRAM-SHA-1`, `MONGODB-CR`, `MONGODB-AWS`, and `X.509`. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -In this guide, you can find sample code for connection to MongoDB with each -authentication mechanism available in the MongoDB Community Edition: -``DEFAULT``, ``SCRAM-SHA-256``, ``SCRAM-SHA-1``, ``MONGODB-CR``, -``MONGODB-AWS``, and ``X.509``. - -``DEFAULT`` ------------ - -The ``DEFAULT`` authentication mechanism is a fallback setting that instructs -the driver to negotiate the first authentication mechanism supported by the -server in the following order of preference: - -#. ``SCRAM-SHA-256`` -#. ``SCRAM-SHA-1`` -#. ``MONGODB-CR`` - -If the ``DEFAULT`` option is specified, the driver first attempts to -authenticate using ``SCRAM-SHA-256``. If the version of the MongoDB instance -does not support that mechanism, the driver attempts to authenticate using -``SCRAM-SHA-1``. If the instance does not support that mechanism either, -the driver attempts to authenticate using ``MONGODB-CR``. - -You can specify this authentication mechanism by setting the ``authMechanism`` -parameter to ``DEFAULT`` in the -:manual:`connection string `, or by omitting -the parameter since it is the default value. Also include your username and -password as shown in the code below. - -.. important:: - Always **URI encode** the username and password using the - ``encodeURIComponent`` method to ensure they are correctly parsed. - -.. literalinclude:: /code-snippets/authentication/default.js - :language: javascript - -For more information on the challenge-response (CR) and salted -challenge-response authentication mechanisms (SCRAM) that MongoDB supports, -see the :manual:`SCRAM ` section of the manual. - -``SCRAM-SHA-256`` ------------------ - -.. note:: - - ``SCRAM-SHA-256`` is the default authentication method for MongoDB starting - in version 4.0 - -``SCRAM-SHA-256`` is a salted challenge-response authentication mechanism -(SCRAM) that uses your username and password, encrypted with the ``SHA-256`` -algorithm to authenticate your user. - -You can specify this authentication mechanism by setting the ``authMechanism`` -to the value ``SCRAM-SHA-256`` in the -:manual:`connection string ` as shown in the -following sample code. - -.. important:: - Always **URI encode** the username and password using the - ``encodeURIComponent`` method to ensure they are correctly parsed. - -.. literalinclude:: /code-snippets/authentication/sha256.js - :language: javascript - -``SCRAM-SHA-1`` ---------------- - -.. note:: - ``SCRAM-SHA-1`` is the default authentication method for MongoDB versions - 3.0, 3.2, 3.4, and 3.6. - -``SCRAM-SHA-1`` is a salted challenge-response mechanism (SCRAM) that uses your -username and password, encrypted with the ``SHA-1`` algorithm to authenticate -your user. - -You can specify this authentication mechanism by setting the ``authMechanism`` -parameter to the value ``SCRAM-SHA-1`` in the -:manual:`connection string ` as shown -in the following sample code. - -.. important:: - Always **URI encode** the username and password using the - ``encodeURIComponent`` method to ensure they are correctly parsed. - -.. literalinclude:: /code-snippets/authentication/sha1.js - :language: javascript - -``MONGODB-CR`` --------------- - -.. warning:: - MONGODB-CR was deprecated starting in MongoDB 3.6, and is no longer supported as of MongoDB 4.0 - -``MONGODB-CR`` is a challenge-response authentication mechanism that uses your -username and password to authenticate your user. - -You can specify this option by setting the ``authMechanism`` parameter to value -``MONGODB-CR`` in the -:manual:`connection string ` as shown -in the following sample code. - -.. important:: - Always **URI encode** the username and password using the - ``encodeURIComponent`` method to ensure they are correctly parsed. - -.. literalinclude:: /code-snippets/authentication/cr.js - :language: javascript - -.. important:: - If you have upgraded the authentication schema from MONGODB-CR to SCRAM, - any ``MONGODB-CR`` user authentication requests fail. - -.. _mongodb-aws: - -``MONGODB-AWS`` ---------------- - -.. note:: - The MONGODB-AWS authentication mechanism is available only in MongoDB - versions 4.4 and later. - -The ``MONGODB-AWS`` authentication mechanism uses your Amazon Web Services -Identity and Access Management (AWS IAM) credentials to authenticate your -user. If you do not already have the `AWS signature library -`__, use the following -``npm`` command to install it: - -.. code-block:: bash - - npm install aws4 - -To connect to a MongoDB instance with ``MONGODB-AWS`` authentication -enabled, specify the ``MONGODB-AWS`` authentication mechanism. - -The driver checks for your credentials in the following sources in order: - -1. Connection string -#. Environment variables -#. Web identity token file -#. AWS ECS endpoint specified in ``AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`` -#. AWS EC2 endpoint. For more information, see `IAM Roles for Tasks - `_. - -.. important:: - - The driver only reads the credentials from the first method that it detects - in the order as given by the preceding list. For example, if you specify - your AWS credentials in the connection string, the driver ignores any - credentials that you specified in environment variables. - -.. tabs:: - - .. tab:: Connection String - :tabid: connection string - - To connect to your MongoDB instance with a connection string, pass - your ``AWS_ACCESS_KEY_ID`` and ``AWS_SECRET_ACCESS_KEY`` - credentials to the driver when you attempt to connect. If your AWS - login requires a session token, include your ``AWS_SESSION_TOKEN`` as well. - - The following code shows an example of specifying the ``MONGODB-AWS`` - authentication mechanism and credentials with a connection string: - - .. important:: - - Always **URI encode** the username and certificate file path using the - ``encodeURIComponent`` method to ensure they are correctly parsed. - - .. literalinclude:: /code-snippets/authentication/aws.js - :language: javascript - - .. tab:: Environment Variables - :tabid: environment variables - - To authenticate to your MongoDB instance using AWS credentials stored in - environment variables, set the following variables by using - a shell: - - .. code-block:: bash - - export AWS_ACCESS_KEY_ID= - export AWS_SECRET_ACCESS_KEY= - export AWS_SESSION_TOKEN= - - .. note:: - - Omit the line containing ``AWS_SESSION_TOKEN`` if you don't need an AWS - session token for that role. - - After you've set the preceding environment variables, specify the ``MONGODB-AWS`` - authentication mechanism in your connection string as shown in the following example: - - .. literalinclude:: /code-snippets/authentication/aws-env-variable.js - :language: javascript - - .. tab:: Web Identity Token File - :tabid: web-identity-token-file - - You can use the OpenID Connect (OIDC) token obtained from a web identity - provider to authenticate to Amazon Elastic Kubernetes Service (EKS) or - other services. - - To authenticate with your OIDC token you must first install - `@aws-sdk/credential-providers - `__. You can - install this dependency using the following ``npm`` command: - - .. code-block:: bash - - npm install @aws-sdk/credential-providers - - Next, create a file that contains your OIDC token. Then - set the absolute path to this file in an environment variable by using - a shell as shown in the following example: - - .. code-block:: bash - - export AWS_WEB_IDENTITY_TOKEN_FILE= - - AWS recommends using regional AWS STS endpoints instead of global - endpoints to reduce latency, build-in redundancy, and increase session token validity. - To set the AWS region, set `AWS_REGION `__ - and `AWS_STS_REGIONAL_ENDPOINTS `__ - as environment variables, as shown in the following example: - - .. code-block:: bash - - export AWS_STS_REGIONAL_ENDPOINTS=regional // Enables regional endpoints - export AWS_REGION=us-east-1 // Sets your AWS region - - If both these environment variables aren't set, the default region is - ``us-east-1``. For a list of available AWS regions, see the - `Regional Endpoints `__ - section of the AWS Service Endpoints reference in the AWS documentation. - - .. warning:: Consult your SDK's Documentation for Setting an AWS Region - - You cannot set your AWS region with environment variables for all SDKs, - as in the above example. See your SDK's specific documentation for - configuring an AWS region. - - After you've set the preceding environment variables, specify the ``MONGODB-AWS`` - authentication mechanism in your connection string as shown in the following example: - - .. literalinclude:: /code-snippets/authentication/aws-env-variable.js - :language: javascript - -.. important:: Retrieval of AWS Credentials - - Starting in version 4.11, when you install the optional - ``aws-sdk/credential-providers`` dependency, the driver uses the AWS SDK - to retrieve credentials from the environment. As a result, if you - have a shared AWS credentials file or config file, the driver will - use those credentials by default. - - You can override this behavior by performing one of the following - actions: - - - Set ``AWS_SHARED_CREDENTIALS_FILE`` variable in your shell to point - to your credentials file. - - Set the equivalent environment variable in your application to point - to your credentials file. - - Create an AWS profile for your MongoDB credentials and set the - ``AWS_PROFILE`` environment variable to that profile name. - -``X.509`` ---------- - -.. note:: - The X.509 authentication mechanism is only available in MongoDB versions - 2.6 and later. - -The ``X.509`` authentication mechanism uses -:wikipedia:`TLS ` with X.509 certificates to -authenticate by retrieving the distinguished name (DN) from the -client certificate. - -You can specify this authentication mechanism by setting the following -parameters of your :manual:`connection string `: - -- Set the ``authMechanism`` parameter to ``MONGODB-X509`` -- Set the ``tls`` parameter to ``true`` - -Pass the location of your client certificate file as the value of -``tlsCertificateKeyFile`` as a parameter of the connection URI. - -.. important:: - Always **URI encode** the certificate file path using the - ``encodeURIComponent`` method to ensure it is parsed correctly. - -.. literalinclude:: /code-snippets/authentication/x509.js - :language: javascript - -.. tip:: - - To learn more about enabling TLS on a connection, see - :ref:`node-connect-tls`. - -TLS Options -~~~~~~~~~~~ - -The following table describes the TLS options that you can set in a -connection URI. - -.. list-table:: - :widths: 35 12 10 43 - :header-rows: 1 - - * - Parameter Name - - Type - - Default Value - - Description - - * - ``tls`` - - boolean - - ``false`` - - Specifies whether to enable TLS on the connection. - - * - ``tlsInsecure`` - - boolean - - ``false`` - - Specifies whether to allow invalid certificates and mismatched - hostnames. When set to ``true``, this is equivalent to setting - ``tlsAllowInvalidCertificates`` and ``tlsAllowInvalidHostnames`` to - ``true``. - - * - ``tlsCAFile`` - - string - - - - Path to file that contains a single or bundle of trusted certificate - authorities used in a TLS connection. - - * - ``tlsCertificateKeyFile`` - - string - - - - Path to the client certificate file or the client private key file. If - both are required, the two must be concatenated into a single file. - - * - ``tlsCertificateKeyFilePassword`` - - buffer or string - - - - String or buffer that contains the password to decrypt the client - private key. - - * - ``tlsAllowInvalidCertificates`` - - boolean - - ``false`` - - Specifies whether the driver permits an invalid certificate to be used - to connect. - - * - ``tlsAllowInvalidHostnames`` - - boolean - - ``false`` - - Specifies whether the driver raises an error when there is a mismatch between the - server hostname and TLS certificate hostname. 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/bson/undefined-values.txt b/source/fundamentals/bson/undefined-values.txt deleted file mode 100644 index e1ebbef71..000000000 --- a/source/fundamentals/bson/undefined-values.txt +++ /dev/null @@ -1,130 +0,0 @@ -.. _node-undefined-values: - -================ -Undefined Values -================ - -.. meta:: - :description: Learn to control the serialization of undefined values in MongoDB Node.js Driver by using the ignoreUndefined setting at various levels. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -Overview --------- - -In this guide, you can learn to control how the driver serializes -``undefined`` values. By default, the driver serializes ``undefined`` values -as ``null`` values during write operations. - -.. _nodejs-specify-ignoreundefined: - -Ignore Undefined Values ------------------------ - -To make the driver ignore fields with -``undefined`` values during serialization, set the -``ignoreUndefined`` setting to ``true``. When you specify this setting, -the driver *does not* serialize fields with ``undefined`` values. - -The following example inserts two documents. The first insert operation has -the ``ignoreUndefined`` setting set to ``true``, so the driver does not -serialize the ``salesTax`` field in that operation. The second operation -inserts a document that has the ``salesTax`` field with a ``null`` value: - -.. code-block:: javascript - :emphasize-lines: 6 - - await myColl.insertOne( - { - state: "Montana", - salesTax: undefined, - }, - { ignoreUndefined: true } - ); - - await myColl.insertOne({ - state: "New Hampshire", - salesTax: undefined, - }); - -The documents appear in the collection as follows: - -.. code-block:: javascript - :copyable: false - - { - _id: ..., - state: "Montana", - }, - { - _id: ..., - state: "New Hampshire", - salesTax: null - } - -.. _nodejs-ignoreundefined-scope: - -Set the Scope for Serializing Undefined Values -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can specify the ``ignoreUndefined`` setting at the following levels: - -- The client level -- The database level -- The collection level -- The operation level - -The ``ignoreUndefined`` setting automatically applies to the scope of the -object instance in which you specified it and any other objects created -from that instance. - -For example, if you set the ``ignoreUndefined`` setting when -instantiating a database object, any collection instance created from -that object inherits the setting. Furthermore, any operations that you -call on that collection instance also inherit the setting. - -The following example performs an find-and-update operation that -inherits the ``ignoreUndefined`` setting from the ``myDB`` database -object. This operation does not produce any data changes because the -driver ignores the ``gasTax`` field: - -.. code-block:: javascript - - const myDB = client.db("test", { ignoreUndefined: true }); - - // The collection inherits the ignoreUndefined setting - const myColl = myDB.collection("states"); - - // Any write operation will not serialize undefined values - await myColl.findOneAndUpdate( - { state: "Georgia" }, - { $set: { gasTax: undefined } } - ); - -You can specify the ``ignoreUndefined`` setting again at any level to -override any inherited settings. - -For example, if you set ``ignoreUndefined`` to ``true`` on your -collection object, you can override the setting in individual write -operations that you execute on that collection. - -.. code-block:: javascript - :emphasize-lines: 1, 12 - - const myColl = myDB.collection("states", { ignoreUndefined: true }); - - // The insert operation will not serialize undefined values - await myColl.insertOne({ - state: "South Dakota", - capitalGainsTax: undefined, - }); - - // The insert operation will serialize undefined values - await myColl.insertOne( - { state: "Texas", capitalGainsTax: undefined }, - { ignoreUndefined: false } - ); diff --git a/source/fundamentals/bson/utf8-validation.txt b/source/fundamentals/bson/utf8-validation.txt deleted file mode 100644 index a31e7e72f..000000000 --- a/source/fundamentals/bson/utf8-validation.txt +++ /dev/null @@ -1,121 +0,0 @@ -.. _nodejs-utf-8-validation: - -================ -UTF-8 Validation -================ - -.. meta:: - :description: Learn how to enable or disable UTF-8 validation in the MongoDB Node.js Driver to manage data encoding and processing overhead. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -Overview --------- - -In this guide, you can learn how to enable or disable the {+driver-short+}'s -**UTF-8** validation feature. UTF-8 is a character encoding specification -that ensures compatibility and consistent presentation across most operating -systems, applications, and language character sets. - -If you *enable* validation, the driver throws an error when it attempts to -convert data that contains invalid UTF-8 characters. The validation adds -processing overhead since it needs to check the data. - -If you *disable* validation, your application avoids the validation processing -overhead, but cannot guarantee consistent presentation of invalid UTF-8 data. - -By default, the driver enables UTF-8 validation on data from MongoDB. -It checks incoming documents for any characters that are not encoded in a -valid UTF-8 format when it parses data sent from MongoDB to your application. - -.. note:: - - This version of the {+driver-short+} automatically substitutes invalid - `lone surrogates `__ - with the `replacement character `__ - before validation when you send data to MongoDB. Therefore, the validation - only throws an error when the setting is enabled and the driver - receives invalid UTF-8 document data from MongoDB. - -Read the sections below to learn how to set UTF-8 validation using the -{+driver-short+}. - -.. _nodejs-specify-utf-8-validation: - -Specify the UTF-8 Validation Setting ------------------------------------- - -You can specify whether the driver performs UTF-8 validation by -defining the ``enableUtf8Validation`` setting in the options parameter -when you create a client, reference a database or collection, or call a -CRUD operation. If you omit the setting, the driver enables UTF-8 validation. - -See the following for code examples that demonstrate how to disable UTF-8 -validation on the client, database, collection, or CRUD operation: - -.. code-block:: javascript - - // disable UTF-8 validation on the client - new MongoClient('', { enableUtf8Validation: false }); - - // disable UTF-8 validation on the database - client.db('', { enableUtf8Validation: false }); - - // disable UTF-8 validation on the collection - db.collection('', { enableUtf8Validation: false }); - - // disable UTF-8 validation on a specific operation call - await myColl.findOne({ title: 'Cam Jansen'}, { enableUtf8Validation: false }); - -If your application reads invalid UTF-8 from MongoDB while the -``enableUtf8Validation`` option is enabled, it throws a ``BSONError`` that -contains the following message: - -.. code-block:: - - Invalid UTF-8 string in BSON document - -.. _nodejs-utf-8-validation-scope: - -Set the Validation Scope -~~~~~~~~~~~~~~~~~~~~~~~~ - -The ``enableUtf8Validation`` setting automatically applies to the scope of the -object instance on which you included it, and any other objects created by -calls on that instance. - -For example, if you include the option on the call to instantiate a database -object, any collection instance you construct from that object inherits -the setting. Any operations you call on that collection instance also -inherit the setting. - -.. code-block:: javascript - - const database = client.db('books', { enableUtf8Validation: false }); - - // The collection inherits the UTF-8 validation disabled setting from the database - const myColl = database.collection('mystery'); - - // CRUD operation runs with UTF-8 validation disabled - await myColl.findOne({ title: 'Encyclopedia Brown' }); - -You can override the setting at any level of scope by including it when -constructing the object instance or when calling an operation. - -For example, if you disable validation on the collection object, you can -override the setting in individual CRUD operation calls on that -collection. - -.. code-block:: javascript - - const collection = database.collection('mystery', { enableUtf8Validation: false }); - - // CRUD operation runs with UTF-8 validation enabled - await myColl.findOne({ title: 'Trixie Belden' }, { enableUtf8Validation: true }); - - // CRUD operation runs with UTF-8 validation disabled - await myColl.findOne({ title: 'Enola Holmes' }); diff --git a/source/fundamentals/collations.txt b/source/fundamentals/collations.txt deleted file mode 100644 index a4474eb21..000000000 --- a/source/fundamentals/collations.txt +++ /dev/null @@ -1,317 +0,0 @@ -.. _node-fundamentals-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/fundamentals/connection/connect.txt b/source/fundamentals/connection/connect.txt deleted file mode 100644 index 17fb36766..000000000 --- a/source/fundamentals/connection/connect.txt +++ /dev/null @@ -1,164 +0,0 @@ -.. _node-connect-to-mongodb: - -================ -Connection Guide -================ - -.. 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 - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -This guide shows you how to connect to a -`MongoDB Atlas deployment `__, -a MongoDB instance, or a replica set using the Node.js driver. - -.. _node-connection-uri: - -Connection URI --------------- - -The **connection URI** is the set of instructions that the driver uses to connect to a -MongoDB deployment. It tells the driver how to connect to MongoDB and how to behave -while connected. The following example shows each part of the connection URI: - -.. figure:: /includes/figures/dns_seedlist_connection_string_parts.png - :alt: Each part of the connection string - -In this example, we connect to an Atlas MongoDB deployment that has a -DNS SRV record. For more details, see the -:manual:`DNS Seed List Connection Format -` -documentation. This format offers flexibility in deployment and the -ability to change the servers in rotation without reconfiguring clients. - -.. note:: - - To learn how to retrieve your connection string in Atlas, see the - :atlas:`Atlas driver connection guide `. - -If you are connecting to an instance or replica set that does not have a -DNS SRV address, you must use ``mongodb`` for the protocol, which specifies -the :manual:`Standard Connection String Format -`. - -After the protocol, the next part of the connection string contains credentials -if you are using password-based authentication. Replace the value of ``user`` -with your username and ``pass`` with your password. If you are using an -authentication mechanism that does not require a username and password, omit -this part of the connection URI. - -The next part of the connection string specifies the hostname or IP address of -your MongoDB instance, followed by the port number. In the example above, we use -``sample.host`` as the hostname and ``27017`` as the port. Replace these values -to point to your MongoDB instance. - -The last part of the connection string contains connection and authentication -options as parameters. In the example above, we set two connection options: -``maxPoolSize=20`` and ``w=majority``. For more information on connection -options, skip to the :ref:`node-connection-options` section. - -.. _connect-sample-node-driver: - -Atlas Connection Example ------------------------- - -You must create a client to connect to a MongoDB deployment on Atlas. To create -a client, construct an instance of ``MongoClient``, passing in your -URI and a ``MongoClientOptions`` object. - -.. tip:: Reuse Your Client - - As each ``MongoClient`` represents a pool of connections to the - database, most applications only require a single instance of a - ``MongoClient``, even across multiple requests. To learn more about - how connection pools work in the driver, see the :ref:`FAQ page - `. - -Use the ``serverApi`` option in your ``MongoClientOptions`` object to -enable the {+stable-api+} feature, which forces the server to run operations -with behavior compatible with the specified API version. - -The following code shows how you can specify the connection string and the -{+stable-api+} client option when connecting to a MongoDB deployment on Atlas and -verify that the connection is successful: - -.. literalinclude:: /code-snippets/connection/stable-api-connect.js - :language: javascript - -.. note:: - - The {+driver-short+} automatically calls the ``MongoClient.connect()`` - method when using the client to perform CRUD operations on your MongoDB deployment. - Call the ``MongoClient.connect()`` method explicitly if you want to verify that the - connection is successful. - -To learn more about the Stable -API feature, see the :ref:`{+stable-api+} page `. - -.. _node-other-ways-to-connect: - -Other Ways to Connect to MongoDB --------------------------------- - -If you are connecting to a single {+mdb-server+} instance or replica set -that is not hosted on Atlas, see the following sections to find out how to -connect. - -Connect to a {+mdb-server+} on Your Local Machine -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. include:: /includes/localhost-connection.rst - -To test whether you can connect to your server, replace the connection -string in the :ref:`Connect to MongoDB ` code -example and run it. - -Connect to a Replica Set -^^^^^^^^^^^^^^^^^^^^^^^^ - -A MongoDB replica set deployment is a group of connected instances that -store the same set of data. This configuration of instances provides data -redundancy and high data availability. - -To connect to a replica set deployment, specify the hostname and port numbers -of each instance, separated by a comma, and the replica set name as the value -of the ``replicaSet`` parameter in the connection string. - -.. code-block:: none - - mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myRs - -When making a connection, the driver takes the following actions by default: - -- Discovers all replica set members when given the address of any one member. -- Dispatches operations to the appropriate member, such as write against the **primary**. - -.. tip:: Specify all hosts - - To ensure connectivity if one host is unavailable, provide the full - list of hosts when connecting to a replica set. - -Direct Connection -^^^^^^^^^^^^^^^^^ - -To force your operations to run on the host specified in your connection -URI, you can specify the ``directConnection`` connection option. If you -specify this option, you must use the standard connection URI format. The -driver does not accept the DNS seedlist connection format (SRV) when you -specify this option. - -When you specify ``directConnection`` and connect to a secondary member of the -replica set, your write operations fail because the client isn't -connected to the primary member. To perform read operations, you must -enable secondary reads. See the :manual:`read preference options ` -for more information. 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/read-operations/limit.txt b/source/fundamentals/crud/read-operations/limit.txt deleted file mode 100644 index eb15c2694..000000000 --- a/source/fundamentals/crud/read-operations/limit.txt +++ /dev/null @@ -1,139 +0,0 @@ -.. _node-fundamentals-limit: - -==================================== -Limit the Number of Returned Results -==================================== - -.. meta:: - :description: Use the limit() method in the MongoDB Node.js Driver to cap the number of documents returned in a read operation, with examples of combining it with sort and skip options for pagination. - -.. default-domain:: mongodb - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -Overview --------- - -Use ``limit`` to cap the number of documents that can be returned from a -read operation. ``limit`` functions as a cap on the maximum number of -documents that the operation can return, but the operation can return -a smaller number of documents if there are not enough documents present -to reach the limit. If ``limit`` is used with the -:doc:`skip ` method, the skip applies -first and the limit only applies to the documents left over after -the skip. - -Sample Documents -~~~~~~~~~~~~~~~~ - -To follow the examples in this guide, use the following code snippet to insert documents -that describe books into the ``myDB.books`` collection: - -.. code-block:: javascript - - const myDB = client.db("myDB"); - const myColl = myDB.collection("books"); - - await myColl.insertMany([ - { "_id": 1, "name": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 }, - { "_id": 2, "name": "Les Misérables", "author": "Hugo", "length": 1462 }, - { "_id": 3, "name": "Atlas Shrugged", "author": "Rand", "length": 1088 }, - { "_id": 4, "name": "Infinite Jest", "author": "Wallace", "length": 1104 }, - { "_id": 5, "name": "Cryptonomicon", "author": "Stephenson", "length": 918 }, - { "_id": 6, "name": "A Dance With Dragons", "author": "Martin", "length": 1104 }, - ]); - -.. include:: /includes/access-cursor-note.rst - -Limit ------ - -The following example queries the collection to return the top three -longest books. It matches all documents because the query filter is -empty. Then, it applies a descending ``sort`` on the ``length`` field to -return longer books before shorter books and a ``limit`` to -return only the ``3`` first results: - -.. code-block:: javascript - :emphasize-lines: 4 - - // define an empty query document - const query = {}; - // sort in descending (-1) order by length - const sort = { length: -1 }; - const limit = 3; - const cursor = myColl.find(query).sort(sort).limit(limit); - for await (const doc of cursor) { - console.dir; - } - -The code example above outputs the following three documents, sorted by -length: - -.. code-block:: json - :copyable: false - - { "_id": 2, "title": "Les Misérables", "author": "Hugo", "length": 1462 } - { "_id": 6, "title": "A Dance With Dragons", "author": "Martin", "length": 1104 } - { "_id": 4, "title": "Infinite Jest", "author": "Wallace", "length": 1104 } - -.. note:: - - The order in which you call ``limit`` and ``sort`` does not matter - because the driver reorders the calls to apply the sort first and the - limit after it. The following two calls are equivalent: - - .. code-block:: javascript - - myColl.find(query).sort({ length: -1 }).limit(3); - myColl.find(query).limit(3).sort({ length: -1 }); - -You can also apply ``sort`` and ``limit`` by specifying them in an -``options`` object in your call to the ``find()`` method. The following two -calls are equivalent: - -.. code-block:: javascript - - myColl.find(query).sort({ length: -1 }).limit(3); - myColl.find(query, { sort: { length: -1 }, limit: 3 }); - -For more information on the ``options`` settings for the ``find()`` -method, see the -`API documentation on find() <{+api+}/classes/Collection.html#find>`__. - -Skip ----- - -To see the next three books in the results, append the ``skip()`` method, -passing the number of documents to bypass as shown below: - -.. code-block:: javascript - :emphasize-lines: 6,7 - - // define an empty query document - const query = {}; - // sort in descending (-1) order by length - const sort = { length: -1 }; - const limit = 3; - const skip = 3; - const cursor = myColl.find(query).sort(sort).limit(limit).skip(skip); - for await (const doc of cursor) { - console.dir; - } - -This operation returns the documents that describe the fourth through sixth -books in order of longest-to-shortest length: - -.. code-block:: json - :copyable: false - - { "_id": 3, "title": "Atlas Shrugged", "author": "Rand", "length": 1088 } - { "_id": 5, "title": "Cryptonomicon", "author": "Stephenson", "length": 918 } - { "_id": 1, "title": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 } - -You can combine skip and limit in this way to implement paging for your -collection, returning only small "slices" of the collection at once. diff --git a/source/fundamentals/crud/read-operations/skip.txt b/source/fundamentals/crud/read-operations/skip.txt deleted file mode 100644 index 07e6c2460..000000000 --- a/source/fundamentals/crud/read-operations/skip.txt +++ /dev/null @@ -1,95 +0,0 @@ -.. _node-fundamentals-skip: - -===================== -Skip Returned Results -===================== - -.. meta:: - :description: Use the skip option in MongoDB Node.js Driver read operations to omit a specified number of documents from the beginning of the result set, often combined with the sort option for ordered results. - -.. default-domain:: mongodb - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -Overview --------- - -Use ``skip`` to omit documents from the beginning of the list of -returned documents for a read operation. You can combine ``skip`` with -:doc:`sort ` to omit the top -(for descending order) or bottom (for ascending order) results for a -given query. Since the :manual:`order of documents returned -` is not guaranteed in -the absence of a sort, using ``skip`` without using ``sort`` omits -arbitrary documents. - -If the value of ``skip`` exceeds the number of matched documents for -a query, then that query returns no documents. - -Sample Documents -~~~~~~~~~~~~~~~~ - -To follow the examples in this guide, use the following code snippet to insert documents -that describe fruits into the ``myDB.fruits`` collection: - -.. code-block:: javascript - - const myDB = client.db("myDB"); - const myColl = myDB.collection("fruits"); - - await myColl.insertMany([ - { "_id": 1, "name": "apples", "qty": 5, "rating": 3 }, - { "_id": 2, "name": "bananas", "qty": 7, "rating": 1 }, - { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 }, - { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 }, - ]); - -.. include:: /includes/access-cursor-note.rst - -Example -------- - -In the following example, we query the collection with a filter that -matches all the documents and pass options that specifies ``sort`` and -``skip`` commands as query options. The sort option specifies that fruit -documents that have higher ``rating`` values are returned before ones with lower -ratings. The skip option specifies that the first 2 documents are -omitted from the result: - -.. code-block:: javascript - - // define an empty query document - const query = {}; - const options = { - // sort in descending (-1) order by rating - sort : { rating: -1 }, - // omit the first two documents - skip : 2, - } - - const cursor = myColl.find(query, options); - for await (const doc of cursor) { - console.dir(doc); - } - -Since we specified that query skip the first ``2`` documents, the third and fourth highest -rating documents are printed by the code snippet above: - -.. code-block:: json - :copyable: false - - { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 } - { "_id": 2, "name": "bananas", "qty": 7, "rating": 1 } - - -The ``sort`` and ``skip`` options can also be specified as methods chained to -the ``find`` method. The following two commands are equivalent: - -.. code-block:: javascript - - myColl.find(query, { sort: { rating: -1}, skip: 2}); - myColl.find(query).sort({rating: -1}).skip(2); diff --git a/source/fundamentals/crud/read-operations/sort.txt b/source/fundamentals/crud/read-operations/sort.txt deleted file mode 100644 index 889707126..000000000 --- a/source/fundamentals/crud/read-operations/sort.txt +++ /dev/null @@ -1,119 +0,0 @@ -.. _node-fundamentals-sort: - -============ -Sort Results -============ - -.. meta:: - :description: Use the sort function in the MongoDB Node.js Driver to order query results by specified fields and resolve ties with other fields. - -.. default-domain:: mongodb - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -Overview --------- - -Use ``sort`` to change the order in which read operations return -documents. ``Sort`` tells MongoDB to order returned documents by the -values of one or more fields in a certain direction. To sort returned -documents by a field in ascending (lowest first) order, use a value of -``1``. To sort in descending (greatest first) order instead, use ``-1``. -If you do not specify a sort, MongoDB does not guarantee the order of -query results. - -Sample Documents -~~~~~~~~~~~~~~~~ - -Follow the instructions in the examples below to insert data into -the ``myDB.books`` collection and perform a sort on the results of a query. -Consider a collection containing documents that describe books. To -insert this data into a collection, run the following operation: - -.. code-block:: javascript - - const myDB = client.db("myDB"); - const myColl = myDB.collection("books"); - - await myColl.insertMany([ - { "_id": 1, "name": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 }, - { "_id": 2, "name": "Les Misérables", "author": "Hugo", "length": 1462 }, - { "_id": 3, "name": "Atlas Shrugged", "author": "Rand", "length": 1088 }, - { "_id": 4, "name": "Infinite Jest", "author": "Wallace", "length": 1104 }, - { "_id": 5, "name": "Cryptonomicon", "author": "Stephenson", "length": 918 }, - { "_id": 6, "name": "A Dance with Dragons", "author": "Martin", "length": 1104 }, - ]); - -.. include:: /includes/access-cursor-note.rst - -Example -------- - -Pass the following sort document to a read operation to ensure that the -operation returns books with longer lengths before books with shorter -lengths: - -.. code-block:: javascript - :emphasize-lines: 4 - - // define an empty query document - const query = {}; - // sort in descending (-1) order by length - const sort = { length: -1 }; - const cursor = myColl.find(query).sort(sort); - for await (const doc of cursor) { - console.dir(doc); - } - -In this case, the number ``-1`` tells the read operation to sort the -books in descending order by length. ``find()`` returns the following -documents when this sort is used with an empty query: - -.. code-block:: json - :copyable: false - - { "_id": 2, "title": "Les Misérables", "author": "Hugo", "length": 1462 } - { "_id": 4, "title": "Infinite Jest", "author": "Wallace", "length": 1104 } - { "_id": 6, "title": "A Dance with Dragons", "author": "Martin", "length": 1104 } - { "_id": 3, "title": "Atlas Shrugged", "author": "Rand", "length": 1088 } - { "_id": 5, "title": "Cryptonomicon", "author": "Stephenson", "length": 918 } - { "_id": 1, "title": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 } - -Sometimes, the order of two or more documents is ambiguous using a -specified sort. In the above case, both "A Dance with Dragons" and -"Infinite Jest" have ``1104`` pages, so the order in which they are -returned is not guaranteed. To resolve ties in your sorted results in a -repeatable way, add more fields to the sort document: - -.. code-block:: javascript - :emphasize-lines: 4 - - // define an empty query document - const query = {}; - // sort in ascending (1) order by length - const sort = { length: 1, author: 1 }; - const cursor = myColl.find(query).sort(sort); - for await (const doc of cursor) { - console.dir(doc); - } - -With the addition of the ``author`` field to the sort document, the read operation sorts -matching documents first by ``length`` then, if there is a tie, by ``author``. Matched -document fields are compared in the same order as fields are specified in the sort -document. ``find()`` returns the following ordering of documents when this sort is used on -the documents matching the query, sorting ``"Martin"`` before ``"Wallace"`` for the two books with -the same length: - -.. code-block:: json - :copyable: false - - { "_id": 1, "title": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 } - { "_id": 5, "title": "Cryptonomicon", "author": "Stephenson", "length": 918 } - { "_id": 3, "title": "Atlas Shrugged", "author": "Rand", "length": 1088 } - { "_id": 6, "title": "A Dance with Dragons", "author": "Martin", "length": 1104 } - { "_id": 4, "title": "Infinite Jest", "author": "Wallace", "length": 1104 } - { "_id": 2, "title": "Les Misérables", "author": "Hugo", "length": 1462 } diff --git a/source/fundamentals/crud/read-write-pref.txt b/source/fundamentals/crud/read-write-pref.txt deleted file mode 100644 index 6107e624c..000000000 --- a/source/fundamentals/crud/read-write-pref.txt +++ /dev/null @@ -1,245 +0,0 @@ -.. _node-crud-write-read-pref: - -=============================================== -Specify How CRUD Operations Run on Replica Sets -=============================================== - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: node.js, customize, preferences, replica set, consistency - :description: Learn to use the MongoDB Node.js Driver to configure write concern, read concern, and read preference for CRUD operations on replica sets to customize data consistency and availability. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -Overview --------- - -In this guide, you can learn how to use the **write concern**, **read concern**, and -**read preference** configurations to modify the way that MongoDB runs -create, read, update, and delete (CRUD) operations on replica sets. - -You can set write concern, read concern, and read preference options at the following -levels: - -- Client, which sets the *default for all operation executions* unless overridden -- Session -- Transaction -- Database -- Collection - -This list also indicates the increasing order of precedence of the option settings. For -example, if you set a read concern level for a transaction, it will override a read -concern level set for the client. - -These options allow you to customize the causal consistency and availability of the data -in your replica sets. - -Write Concern -------------- - -The write concern specifies the level of acknowledgement requested from MongoDB for write -operations, such as an insert or update, before the operation successfully returns. -Operations that do not specify an explicit write concern inherit the global default write -concern settings. - -For more information, see :manual:`Write Concern ` in the -Server manual. For detailed API documentation, see the `WriteConcern API documentation -<{+api+}/classes/WriteConcern.html>`__. - -The following table describes the ``WriteConcern`` parameters: - -.. list-table:: - :header-rows: 1 - :widths: 25 25 50 - - * - Parameter - - Type - - Description - - * - ``w`` *(optional)* - - `W <{+api+}/types/W.html>`__ - - Requests acknowledgment that the write operation has propagated to a specified - number of ``mongod`` instances or to ``mongod`` instances that are labelled specified tags - - * - ``wtimeoutMS`` *(optional)* - - number - - Specifies a time limit to prevent write operations from blocking indefinitely - - * - ``journal`` *(optional)* - - boolean - - Requests acknowledgment that the write operation has been written to the on-disk journal - -Example: Set the Write Concern for a Single Write Operation -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This code uses custom ``WriteConcern`` settings while creating new a document: - -.. code-block:: js - - myDB.myCollection.insertOne( - { name: "anotherDocumentName" }, - { writeConcern: - { w: 2, wtimeoutMS: 5000 } - } - ); - -Example: Retrieve and Apply an Existing Write Concern -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This code uses the ``fromOptions()`` method to construct a ``WriteConcern`` from the -options of an existing database reference, ``myDB``. Note that ``myDB`` could be replaced -with a reference to any entity that accepts a write concern option. Then the new write -concern is applied to a document, ``myDoc``. - -.. code-block:: js - - const newWriteConcern = WriteConcern.fromOptions(myDB); - const myDoc = { name: "New Document" }; - WriteConcern.apply(myDoc,newWriteConcern); - -Read Concern ------------- - -The read concern specifies the following behaviors: - -- Level of :manual:`causal consistency ` across replica sets - -- `Isolation guarantees - `__ maintained during a query - -You can specify the read concern setting by using the ``level`` parameter. The default -read concern level is ``local``. This means that the client returns the data from the -replica set member that the client is connected to, with no guarantee that the data has -been written to all replica set members. Note that lower read concern level requirements -may reduce latency. - -For more information about read concerns or read concern levels, see -:manual:`Read Concern ` in the Server manual. For more detail on -the ``ReadConcern`` type and definitions of the read concern levels, see the `ReadConcern <{+api+}/classes/ReadConcern.html>`__ in -the API documentation. - -Example: Set the Read Concern Level of an Aggregation -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This code sets the read concern level of an an aggregation to ``"majority"``: - -.. code-block:: js - - const pipeline = [ - {"$match": { - category: "KITCHENWARE", - }}, - {"$unset": [ - "_id", - "category", - ]} - ]; - - result = await myDB.collection("mycollection") - .aggregate( - pipeline, - { readConcern: - { level: "available" } - } - ); - -For more information about aggregates, see the :ref:`nodejs-aggregation` page. - -Example: Change the Read Concern of a Database -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This code changes the read concern level of a database to ``"local"``: - -.. code-block:: js - - const options = { readConcern: { level: "local" } }; - const myDB = client.db("mydb", options); - -Read Preference ---------------- - -The read preference determines which member of a replica set MongoDB reads when running a -query. You can also customize how the server evaluates members. - -For more detailed API documentation, see the `ReadPreference API -documentation <{+api+}/classes/ReadPreference.html>`__. - -The following table describes the ``ReadPreference`` parameters: - -.. list-table:: - :widths: 25 25 50 - :header-rows: 1 - - * - Parameter - - Type - - Description - - * - ``mode`` - - :manual:`ReadPreferenceMode ` - - Specifies a requirement or preference for which replica set - member the server reads from. The default mode, ``primary``, specifies that - operations read from the primary member of the replica set. - - * - ``tags`` *(optional)* - - :manual:`TagSet List ` - - Assigns tags to secondary replica set members to customize how the server evaluates - them. Tags cannot be used with the ``primary`` read preference mode setting. - - * - ``options`` *(optional)* - - `ReadPreferenceOptions <{+api+}/interfaces/ReadPreferenceOptions.html>`__ - - Sets various options, including :manual:`hedge ` - and :manual:`maxStalenessSeconds ` that can be - applied to your read preference. - -Example: Set Read Preference and Concerns for a Transaction -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This code sets the read preference, read concern, and write concern for the operations in -a transaction: - -.. code-block:: js - - const transactionOptions = { - readPreference: "primary", - readConcern: { level: "local" }, - writeConcern: { w: "majority" }, - }; - - const session = client.startSession(); - session.startTransaction(transactionOptions); - // ... - await session.commitTransaction(); - await session.endSession(); - -For more information about transactions, see :ref:`nodejs-transactions`. - -Example: Set the Read Preference of a Cluster in the Connection String -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This code example creates a MongoClient that uses the "secondary" read preference mode -when performing queries on a cluster: - -.. code-block:: js - - const uri = "mongodb+srv://:@?readPreference=secondary&maxStalenessSeconds=120"; - const client = new MongoClient(uri); - -This example also sets the ``maxStalenessSeconds`` option. For more information about connection string options, see the :manual:`Connection String Options ` -section in the manual. - -API Documentation ------------------ - -To learn more about the methods and types mentioned in this guide, see the following API -documentation: - -- `API WriteConcern <{+api+}/classes/WriteConcern.html>`__ -- `API ReadConcern <{+api+}/classes/ReadConcern.html>`__ -- `API ReadPreference <{+api+}/classes/ReadPreference.html>`__ \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations.txt b/source/fundamentals/crud/write-operations.txt deleted file mode 100644 index 018d07b71..000000000 --- a/source/fundamentals/crud/write-operations.txt +++ /dev/null @@ -1,26 +0,0 @@ -================ -Write Operations -================ - -.. meta:: - :description: Learn about the commands for running MongoDB write operations by using the {+driver-long+}. - - -.. toctree:: - :caption: Write Operations - - Insert - Custom Values for _id - Delete - Modify - Update Arrays - 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` -- :doc:`/fundamentals/crud/write-operations/embedded-arrays` -- :doc:`/fundamentals/crud/write-operations/upsert` -- :doc:`/fundamentals/crud/write-operations/bulk` diff --git a/source/fundamentals/crud/write-operations/delete.txt b/source/fundamentals/crud/write-operations/delete.txt deleted file mode 100644 index cfb8c374a..000000000 --- a/source/fundamentals/crud/write-operations/delete.txt +++ /dev/null @@ -1,66 +0,0 @@ -.. _node-fundamentals-delete: - -================ -Delete Documents -================ - -.. meta:: - :description: Learn how to use deleteOne() and deleteMany() methods in the MongoDB Node.js Driver to remove documents from a collection based on specified query criteria. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 1 - :class: singlecol - -Overview --------- - -In this section, we show you how to call the write operations to **remove** -documents from a collection in your MongoDB database. - -Delete ------- - -If you want to remove existing documents from a collection, you can -use ``deleteOne()`` to remove one document or ``deleteMany()`` for one or -more documents. These methods accept a query document that matches the -documents you want to delete. - -You can specify the document or documents to be deleted by the -``deleteOne()`` or ``deleteMany()`` write operations in a JSON object as -follows: - -.. code-block:: javascript - - const doc = { - pageViews: { - $gt: 10, - $lt: 32768 - } - }; - -To delete the first matching document using the ``deleteOne()`` method or -to delete all matching documents using the ``deleteMany()`` method, pass the -document as the method parameter: - -.. code-block:: javascript - - const deleteResult = await myColl.deleteOne(doc); - const deleteManyResult = await myColl.deleteMany(doc); - -You can print the number of documents deleted by the operation by -accessing the ``deletedCount`` field of the result for each of the -method calls above as follows: - -.. code-block:: javascript - - console.dir(deleteResult.deletedCount); - console.dir(deleteManyResult.deletedCount); - -If the delete operation is successful, these statements print the number of documents -deleted by the associated operation. - -To see fully runnable examples and more information on the available options, see the usage -examples for :doc:`deleteOne() ` and -:doc:`deleteMany() `. diff --git a/source/fundamentals/monitoring.txt b/source/fundamentals/monitoring.txt deleted file mode 100644 index cd132fa24..000000000 --- a/source/fundamentals/monitoring.txt +++ /dev/null @@ -1,24 +0,0 @@ -========== -Monitoring -========== - -.. meta:: - :description: Explore cluster, command, and connection pool monitoring in the MongoDB Node.js Driver. - -.. facet:: - :name: genre - :values: reference - -.. toctree:: - :caption: CRUD Operations - - Clusters - Commands - Connection Pool - -- :doc:`Cluster Monitoring `: monitoring - changes in a cluster -- :doc:`Command Monitoring `: monitoring - the execution status of commands -- :doc:`Connection Pool Monitoring `: monitoring - the driver's connection pool \ No newline at end of file diff --git a/source/fundamentals/monitoring/cluster-monitoring.txt b/source/fundamentals/monitoring/cluster-monitoring.txt deleted file mode 100644 index a09f792c0..000000000 --- a/source/fundamentals/monitoring/cluster-monitoring.txt +++ /dev/null @@ -1,346 +0,0 @@ -.. _node-cluster-monitoring: - -================== -Cluster Monitoring -================== - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: code example, node.js, watch - :description: Monitor topology events in a MongoDB instance, replica set, or sharded cluster by subscribing to Server Discovery and Monitoring (SDAM) events with the MongoDB Node.js Driver. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecols - -Overview --------- - -This guide shows you how to monitor topology events in a MongoDB instance, -replica set, or sharded cluster. The driver creates topology events, also -known as Server Discovery and Monitoring (SDAM) events, when there is -a change in the state of the instance or cluster that you connected to. -For example, the driver creates an event when you establish a new connection -or if the cluster elects a new primary. - -The following sections demonstrate how to record topology changes in your application -and explore the information provided in these events. - -Event Subscription Example --------------------------- - -You can access one or more SDAM events using the driver by subscribing to them -in your application. The following example demonstrates connecting to a -replica set and subscribing to one of the SDAM events created by the MongoDB -deployment: - -.. literalinclude:: /code-snippets/monitoring/sdam-subscribe.js - :language: javascript - -Event Descriptions ------------------- - -You can subscribe to any of the following SDAM events: - -.. list-table:: - :widths: 33 67 - :header-rows: 1 - - * - Event Name - - Description - - * - ``serverOpening`` - - Created when a connection to an instance opens. - - * - ``serverClosed`` - - Created when a connection to an instance closes. - - * - ``serverDescriptionChanged`` - - Created when an instance state changes (such as from secondary to - primary). - - * - ``topologyOpening`` - - Created before attempting a connection to an instance. - - * - ``topologyClosed`` - - Created after all instance connections in the topology close. - - * - ``topologyDescriptionChanged`` - - Created when the topology changes, such as an election of a new - primary or a **mongos** proxy disconnecting. - - * - ``serverHeartbeatStarted`` - - Created before issuing a ``hello`` command to a MongoDB instance. - - * - ``serverHeartbeatSucceeded`` - - Created when the ``hello`` command returns successfully from a - MongoDB instance. - - * - ``serverHeartbeatFailed`` - - Created when a ``hello`` command issued to a specific MongoDB - instance fails to return a successful response. - -Example Event Documents ------------------------ - -The following sections show sample output for each type of SDAM event. - -serverDescriptionChanged -^^^^^^^^^^^^^^^^^^^^^^^^ - -.. code-block:: javascript - :copyable: false - - ServerDescriptionChangedEvent { - topologyId: 0, - address: 'localhost:27017', - previousDescription: ServerDescription { - address: 'localhost:27017', - error: null, - roundTripTime: 0, - lastUpdateTime: 1571251089030, - lastWriteDate: null, - opTime: null, - type: 'Unknown', - minWireVersion: 0, - maxWireVersion: 0, - hosts: [], - passives: [], - arbiters: [], - tags: [] - }, - newDescription: ServerDescription { - address: 'localhost:27017', - error: null, - roundTripTime: 0, - lastUpdateTime: 1571251089051, - lastWriteDate: 2019-10-16T18:38:07.000Z, - opTime: { ts: Timestamp, t: 18 }, - type: 'RSPrimary', - minWireVersion: 0, - maxWireVersion: 7, - maxBsonObjectSize: 16777216, - maxMessageSizeBytes: 48000000, - maxWriteBatchSize: 100000, - me: 'localhost:27017', - hosts: [ 'localhost:27017' ], - passives: [], - arbiters: [], - tags: [], - setName: 'rs', - setVersion: 1, - electionId: ObjectID, - primary: 'localhost:27017', - logicalSessionTimeoutMinutes: 30, - '$clusterTime': ClusterTime - } - } - -The ``type`` field of the ``ServerDescription`` object in this event contains -one of the following possible values: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Type - - Description - * - ``Unknown`` - - Unknown instance - * - ``Standalone`` - - Standalone instance - * - ``Mongos`` - - Mongos proxy instance - * - ``PossiblePrimary`` - - At least one server recognizes this as the primary, but is not yet - verified by all instances. - * - ``RSPrimary`` - - Primary instance - * - ``RSSecondary`` - - Secondary instance - * - ``RSArbiter`` - - Arbiter instance - * - ``RSOther`` - - See the `RSGhost and RSOther specification `__ - for more details - * - ``RSGhost`` - - See the `RSGhost and RSOther specification `__ - for more details - -serverHeartbeatStarted -^^^^^^^^^^^^^^^^^^^^^^ - -.. code-block:: javascript - :copyable: false - - ServerHeartbeatStartedEvent { - connectionId: 'localhost:27017' - } - -serverHeartbeatSucceeded -^^^^^^^^^^^^^^^^^^^^^^^^ - -.. code-block:: javascript - :copyable: false - - ServerHeartbeatSucceededEvent { - duration: 1.939997, - reply:{ - hosts: [ 'localhost:27017' ], - setName: 'rs', - setVersion: 1, - isWritablePrimary: true, - secondary: false, - primary: 'localhost:27017', - me: 'localhost:27017', - electionId: ObjectID, - lastWrite: { - opTime: { ts: [Timestamp], t: 18 }, - lastWriteDate: 2019-10-16T18:38:17.000Z, - majorityOpTime: { ts: [Timestamp], t: 18 }, - majorityWriteDate: 2019-10-16T18:38:17.000Z - }, - maxBsonObjectSize: 16777216, - maxMessageSizeBytes: 48000000, - maxWriteBatchSize: 100000, - localTime: 2019-10-16T18:38:19.589Z, - logicalSessionTimeoutMinutes: 30, - minWireVersion: 0, - maxWireVersion: 7, - readOnly: false, - ok: 1, - operationTime: Timestamp, - '$clusterTime': ClusterTime - }, - connectionId: 'localhost:27017' - } - -serverHeartbeatFailed -^^^^^^^^^^^^^^^^^^^^^ - -.. code-block:: javascript - :copyable: false - - ServerHeartbeatFailed { - duration: 20, - failure: MongoError('some error'), - connectionId: 'localhost:27017' - } - -serverOpening -^^^^^^^^^^^^^ - -.. code-block:: javascript - :copyable: false - - ServerOpeningEvent { - topologyId: 0, - address: 'localhost:27017' - } - -serverClosed -^^^^^^^^^^^^ - -.. code-block:: javascript - :copyable: false - - ServerClosedEvent { - topologyId: 0, - address: 'localhost:27017' - } - -topologyOpening -^^^^^^^^^^^^^^^ - -.. code-block:: javascript - :copyable: false - - TopologyOpeningEvent { - topologyId: 0 - } - -topologyClosed -^^^^^^^^^^^^^^ - -.. code-block:: javascript - :copyable: false - - TopologyClosedEvent { - topologyId: 0 - } - -topologyDescriptionChanged -^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. code-block:: javascript - :copyable: false - - TopologyDescriptionChangedEvent { - topologyId: 0, - previousDescription: TopologyDescription { - type: 'ReplicaSetNoPrimary', - setName: null, - maxSetVersion: null, - maxElectionId: null, - servers: Map { - 'localhost:27017' => ServerDescription - }, - stale: false, - compatible: true, - compatibilityError: null, - logicalSessionTimeoutMinutes: null, - heartbeatFrequencyMS: 10000, - localThresholdMS: 15, - options: Object, - error: undefined, - commonWireVersion: null - }, - newDescription: TopologyDescription { - type: 'ReplicaSetWithPrimary', - setName: 'rs', - maxSetVersion: 1, - maxElectionId: null, - servers: Map { - 'localhost:27017' => ServerDescription - }, - stale: false, - compatible: true, - compatibilityError: null, - logicalSessionTimeoutMinutes: 30, - heartbeatFrequencyMS: 10000, - localThresholdMS: 15, - options: Object, - error: undefined, - commonWireVersion: 7 - } - } - -The ``type`` field of the ``TopologyDescription`` object in this event contains -one of the following possible values: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Type - - Description - - * - ``Single`` - - Standalone instance - - * - ``ReplicaSetWithPrimary`` - - Replica set with a primary - - * - ``ReplicaSetNoPrimary`` - - Replica set with no primary - - * - ``Sharded`` - - Sharded cluster - - * - ``Unknown`` - - Unknown topology diff --git a/source/fundamentals/monitoring/command-monitoring.txt b/source/fundamentals/monitoring/command-monitoring.txt deleted file mode 100644 index 6ee286625..000000000 --- a/source/fundamentals/monitoring/command-monitoring.txt +++ /dev/null @@ -1,133 +0,0 @@ -.. _node-command-monitoring: - -================== -Command Monitoring -================== - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: code example, node.js, watch, command status - :description: Monitor the success or failure of MongoDB commands by subscribing to command monitoring events in your application with the MongoDB Node.js Driver. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 1 - :class: singlecols - -Overview --------- - -This guide shows you how to monitor the success or failure of commands -sent by the driver to your MongoDB deployment. - -The following sections demonstrate how to record command status in your -application and explore the information provided in these events. - -Event Subscription Example --------------------------- - -You can access one or more command monitoring events using the driver by -subscribing to them in your application. The following example demonstrates -connecting to a replica set and subscribing to one of the command monitoring -events created by the MongoDB deployment: - -.. literalinclude:: /code-snippets/monitoring/apm-subscribe.js - :language: javascript - -.. note:: - - Command monitoring is disabled by default. To enable command - monitoring, pass the ``monitorCommands`` option as ``true`` to - your ``MongoClient`` constructor. - -Event Descriptions ------------------- - -You can subscribe to any of the following command monitoring events: - -.. list-table:: - :widths: 33 67 - :header-rows: 1 - - * - Event Name - - Description - - * - ``commandStarted`` - - Created when a command is started. - - * - ``commandSucceeded`` - - Created when a command succeeded. - - * - ``commandFailed`` - - Created when a command failed. - -Example Event Documents ------------------------ - -The following sections show sample output for each type of command monitoring event. - -commandStarted -^^^^^^^^^^^^^^ - -.. code-block:: javascript - :copyable: false - - CommandStartedEvent { - requestId: 1534, - databaseName: "app", - commandName: "find", - address: 'localhost:27017', - connectionId: 812613, - command: { - find: { firstName: "Jane", lastName: "Doe" } - } - } - -commandSucceeded -^^^^^^^^^^^^^^^^ - -.. code-block:: javascript - :copyable: false - - CommandSucceededEvent { - requestId: 1534, - commandName: "find", - address: 'localhost:27017', - connectionId: 812613, - duration: 15, - reply: { - cursor: { - firstBatch: [ - { - _id: ObjectId("5e8e2ca217b5324fa9847435"), - firstName: "Jane", - lastName: "Doe" - } - ], - _id: 0, - ns: "app.users" - }, - ok: 1, - operationTime: 1586380205 - } - } - - -commandFailed -^^^^^^^^^^^^^ - -.. code-block:: javascript - :copyable: false - - CommandFailedEvent { - requestId: 1534, - commandName: "find", - address: 'localhost:27017', - connectionId: 812613, - failure: Error("something failed"), - duration: 11 - } diff --git a/source/fundamentals/monitoring/connection-monitoring.txt b/source/fundamentals/monitoring/connection-monitoring.txt deleted file mode 100644 index 0c00c65be..000000000 --- a/source/fundamentals/monitoring/connection-monitoring.txt +++ /dev/null @@ -1,243 +0,0 @@ -.. _node-connection-pool-monitoring: - -========================== -Connection Pool Monitoring -========================== - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: code example, node.js, watch, deployment - :description: Monitor the MongoDB Node.js Driver's connection pool by subscribing to connection pool events to understand and debug your application's connection behavior. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecols - -Overview --------- - -This guide shows you how to monitor the driver's **connection pool**. A -connection pool is a set of open TCP connections your driver maintains -with a MongoDB instance. Connection pools help reduce the number of -network handshakes your application needs to perform and can help your -application run faster. - -The following sections demonstrate how to record connection pool events in your -application and explore the information provided in these events. - -Event Subscription Examples ---------------------------- - -You can access one or more connection pool events using the driver by -subscribing to them in your application. The following example demonstrates -connecting to a replica set and subscribing to one of the connection -pool monitoring events created by the MongoDB deployment: - -.. literalinclude:: /code-snippets/monitoring/cpm-subscribe.js - :language: javascript - -Connection pool monitoring events can aid you in debugging and understanding -the behavior of your application's connection pool. The following example uses connection -pool monitoring events to return a count of checked-out connections in the pool: - -.. literalinclude:: /code-snippets/monitoring/cpm-status.js - :language: javascript - -Event Descriptions ------------------- - -You can subscribe to any of the following connection pool monitoring events: - -.. list-table:: - :widths: 33 67 - :header-rows: 1 - - * - Event Name - - Description - - * - ``connectionPoolCreated`` - - Created when a connection pool is created. - - * - ``connectionPoolReady`` - - Created when a connection pool is ready. - - * - ``connectionPoolClosed`` - - Created when a connection pool is closed before server - instance destruction. - - * - ``connectionCreated`` - - Created when a connection is created, but not necessarily - when it is used for an operation. - - * - ``connectionReady`` - - Created after a connection has successfully completed a - handshake and is ready to be used for operations. - - * - ``connectionClosed`` - - Created when a connection is closed. - - * - ``connectionCheckOutStarted`` - - Created when an operation attempts to acquire a connection for - execution. - - * - ``connectionCheckOutFailed`` - - Created when an operation fails to acquire a connection for - execution. - - * - ``connectionCheckedOut`` - - Created when an operation successfully acquires a connection for - execution. - - * - ``connectionCheckedIn`` - - Created when a connection is checked back into the pool after an operation - is executed. - - * - ``connectionPoolCleared`` - - Created when a connection pool is cleared. - -Example Event Documents ------------------------ - -The following sections show sample output for each type of connection -pool monitoring event. - -connectionPoolCreated -~~~~~~~~~~~~~~~~~~~~~ - -.. code-block:: none - :copyable: false - - ConnectionPoolCreatedEvent { - time: 2023-02-13T15:54:06.944Z, - address: '...', - options: {...} - } - -connectionPoolReady -~~~~~~~~~~~~~~~~~~~ - -.. code-block:: none - :copyable: false - - ConnectionPoolReadyEvent { - time: 2023-02-13T15:56:38.440Z, - address: '...' - } - -connectionPoolClosed -~~~~~~~~~~~~~~~~~~~~ - -.. code-block:: none - :copyable: false - - ConnectionPoolClosedEvent { - time: 2023-02-13T15:56:38.440Z, - address: '...' - } - -connectionCreated -~~~~~~~~~~~~~~~~~ - -.. code-block:: none - :copyable: false - - ConnectionCreatedEvent { - time: 2023-02-13T15:56:38.291Z, - address: '...', - connectionId: 1 - } - -connectionReady -~~~~~~~~~~~~~~~ - -.. code-block:: none - :copyable: false - - ConnectionReadyEvent { - time: 2023-02-13T15:56:38.291Z, - address: '...', - connectionId: 1, - durationMS: 60 - } - -connectionClosed -~~~~~~~~~~~~~~~~ - -.. code-block:: none - :copyable: false - - ConnectionClosedEvent { - time: 2023-02-13T15:56:38.439Z, - address: '...', - connectionId: 1, - reason: 'poolClosed', - serviceId: undefined - } - -connectionCheckOutStarted -~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code-block:: none - :copyable: false - - ConnectionCheckOutStartedEvent { - time: 2023-02-13T15:56:38.291Z, - address: '...', - } - -connectionCheckOutFailed -~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code-block:: none - :copyable: false - - ConnectionCheckOutFailedEvent { - time: 2023-02-13T15:56:38.291Z, - address: '...', - reason: ..., - durationMS: 60 - } - -connectionCheckedOut -~~~~~~~~~~~~~~~~~~~~ - -.. code-block:: none - :copyable: false - - ConnectionCheckedOutEvent { - time: 2023-02-13T15:54:07.188Z, - address: '...', - connectionId: 1, - durationMS: 60 - } - -connectionCheckedIn -~~~~~~~~~~~~~~~~~~~ - -.. code-block:: none - :copyable: false - - ConnectionCheckedInEvent { - time: 2023-02-13T15:54:07.189Z, - address: '...', - connectionId: 1 - } - -connectionPoolCleared -~~~~~~~~~~~~~~~~~~~~~ - -.. code-block:: none - :copyable: false - - ConnectionPoolClearedEvent { - time: 2023-02-13T15:56:38.439Z, - address: '...', - serviceId: undefined, - interruptInUseConnections: true, - } - diff --git a/source/get-started.txt b/source/get-started.txt new file mode 100644 index 000000000..70d1b73a5 --- /dev/null +++ b/source/get-started.txt @@ -0,0 +1,271 @@ +.. _node-get-started: + +=================================== +Get Started with the Node.js Driver +=================================== + +.. 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. +The {+driver-short+} is a library of functions that you can use to connect +to and communicate with MongoDB. + +.. tip:: + + 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. If you prefer to connect to MongoDB using a different +driver or programming language, see our :driver:`list of official drivers <>`. + +.. _node-quick-start-download-and-install: +.. _node-get-started-download-and-install: + +Download and Install +-------------------- + +.. procedure:: + :style: connected + + .. step:: Install dependencies + + Ensure you have the following dependencies installed in + your development environment: + + - Node.js {+min-node-version+} or later + - npm (Node Package Manager) + + To learn how to install Node.js and npm, see + `Downloading and installing Node.js and npm `__ + in the npm documentation. + + .. 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 + + Then, run the following commands to navigate into the + directory and initialize your Node.js project: + + .. code-block:: bash + + cd node_quickstart + npm init -y + + When the initialization command successfully completes, you have a ``package.json`` + file in your ``node_quickstart`` directory. + + .. step:: Install the Node.js Driver + + Run the following command from your project directory to install + the driver: + + .. 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 a new project directory with +the driver dependencies installed. + +.. _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. + +.. _node-quick-start-connection-string: +.. _node-get-started-connection-string: + +Create a Connection String +-------------------------- + +You can connect to your MongoDB deployment by providing a +**connection URI**, also called a *connection string*, which +instructs the driver on how to connect to a MongoDB deployment +and how to behave while connected. + +The connection string includes the hostname or IP address and +port of your deployment, the authentication mechanism, user credentials +when applicable, and connection options. + +.. procedure:: + :style: connected + + .. step:: Find your MongoDB Atlas connection string + + To retrieve your connection string for the deployment that + you created in the :ref:`previous section `, + 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_connection_connect_cluster.png + :alt: The connect button in the clusters section of the Atlas UI + + .. step:: Copy your connection string + + Click the button on the right of the connection string to copy it to + your clipboard, as shown in the following screenshot: + + .. figure:: /includes/figures/atlas_connection_copy_uri_node.png + :alt: The connection string copy button in the Atlas UI + + .. step:: Update the placeholders + + Paste your connection string into a file in your preferred text editor + and replace the ``username`` and ```` placeholders with your + database user's username and password. + + Save this file to a safe location for use in the next section. + +After completing these steps, you have a connection string that +contains your database username and password. + +.. _node-quick-start-connect-to-mongodb: +.. _node-get-started-connect-to-mongodb: + +Connect to MongoDB +------------------ + +.. procedure:: + :style: connected + + .. step:: Create your Node.js application + + In your ``node_quickstart`` directory, create a file called + ``index.js`` for your application. + + 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'); + + // Queries for a movie that has a title value of 'Back to the Future' + const query = { title: 'Back to the Future' }; + const movie = await movies.findOne(query); + + console.log(movie); + } finally { + 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 + + From your project directory, run the following command to start + the application: + + .. code-block:: none + + node index.js + + The output includes details about 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, verify that 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, query +the sample data, and print out the result. + +.. _node-quick-start-next-steps: +.. _node-get-started-next-steps: + +Next Steps +---------- + +Congratulations on completing the quick start tutorial! + +.. include:: /includes/quick-start/troubleshoot.rst + +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-short+} from the following resources: + +- Discover how to configure your MongoDB connection in the + :ref:`Connect to MongoDB ` section. + +- Discover how to perform read and write operations in the + :ref:`CRUD Operations ` section. \ No newline at end of file diff --git a/source/includes/access-cursor-note.rst b/source/includes/access-cursor-note.rst index c3ad63f56..c72bac066 100644 --- a/source/includes/access-cursor-note.rst +++ b/source/includes/access-cursor-note.rst @@ -3,4 +3,4 @@ Your query operation may return a reference to a cursor that contains matching documents. To learn how to examine data stored in the cursor, see the - :doc:`Cursor Fundamentals page `. \ No newline at end of file + :ref:`Access Data From a Cursor page `. diff --git a/source/includes/aggregation/atlas-vector-search-example.js b/source/includes/aggregation/atlas-vector-search-example.js new file mode 100644 index 000000000..b666e30ad --- /dev/null +++ b/source/includes/aggregation/atlas-vector-search-example.js @@ -0,0 +1,51 @@ +const { MongoClient } = require("mongodb"); + +// Replace with the connection string to your Atlas cluster to connect +const uri = ""; + +const client = new MongoClient(uri); + +async function run() { + try { + await client.connect(); + + // Sets the namespace + const database = client.db("sample_mflix"); + const coll = database.collection("embedded_movies"); + + // Defines the pipeline + const agg = [ + { + '$vectorSearch': { + 'index': 'vector_index', + 'path': 'plot_embedding', + 'queryVector': Binary.fromFloat32Array(Float32Array.from([ + -0.0016261312, -0.028070757, -0.011342932, -0.012775794, -0.0027440966, 0.008683807, -0.02575152, -0.02020668, -0.010283281, -0.0041719596, 0.021392956, 0.028657231, -0.006634482, 0.007490867, 0.018593878, 0.0038187427, 0.029590257, -0.01451522, 0.016061379, 0.00008528442, -0.008943722, 0.01627464, 0.024311995, -0.025911469, 0.00022596726, -0.008863748, 0.008823762, -0.034921836, 0.007910728, -0.01515501, 0.035801545, -0.0035688248, -0.020299982, -0.03145631, -0.032256044, -0.028763862, -0.0071576433, -0.012769129, 0.012322609, -0.006621153, 0.010583182, 0.024085402, -0.001623632, 0.007864078, -0.021406285, 0.002554159, 0.012229307, -0.011762793, 0.0051682983, 0.0048484034, 0.018087378, 0.024325324, -0.037694257, -0.026537929, -0.008803768, -0.017767483, -0.012642504, -0.0062712682, 0.0009771782, -0.010409906, 0.017754154, -0.004671795, -0.030469967, 0.008477209, -0.005218282, -0.0058480743, -0.020153364, -0.0032805866, 0.004248601, 0.0051449724, 0.006791097, 0.007650814, 0.003458861, -0.0031223053, -0.01932697, -0.033615597, 0.00745088, 0.006321252, -0.0038154104, 0.014555207, 0.027697546, -0.02828402, 0.0066711367, 0.0077107945, 0.01794076, 0.011349596, -0.0052715978, 0.014755142, -0.019753495, -0.011156326, 0.011202978, 0.022126047, 0.00846388, 0.030549942, -0.0041386373, 0.018847128, -0.00033655585, 0.024925126, -0.003555496, -0.019300312, 0.010749794, 0.0075308536, -0.018287312, -0.016567878, -0.012869096, -0.015528221, 0.0078107617, -0.011156326, 0.013522214, -0.020646535, -0.01211601, 0.055928253, 0.011596181, -0.017247654, 0.0005939711, -0.026977783, -0.003942035, -0.009583511, -0.0055248477, -0.028737204, 0.023179034, 0.003995351, 0.0219661, -0.008470545, 0.023392297, 0.010469886, -0.015874773, 0.007890735, -0.009690142, -0.00024970944, 0.012775794, 0.0114762215, 0.013422247, 0.010429899, -0.03686786, -0.006717788, -0.027484283, 0.011556195, -0.036068123, -0.013915418, -0.0016327957, 0.0151016945, -0.020473259, 0.004671795, -0.012555866, 0.0209531, 0.01982014, 0.024485271, 0.0105431955, -0.005178295, 0.033162415, -0.013795458, 0.007150979, 0.010243294, 0.005644808, 0.017260984, -0.0045618312, 0.0024725192, 0.004305249, -0.008197301, 0.0014203656, 0.0018460588, 0.005015015, -0.011142998, 0.01439526, 0.022965772, 0.02552493, 0.007757446, -0.0019726837, 0.009503538, -0.032042783, 0.008403899, -0.04609149, 0.013808787, 0.011749465, 0.036388017, 0.016314628, 0.021939443, -0.0250051, -0.017354285, -0.012962398, 0.00006107364, 0.019113706, 0.03081652, -0.018114036, -0.0084572155, 0.009643491, -0.0034721901, 0.0072642746, -0.0090636825, 0.01642126, 0.013428912, 0.027724205, 0.0071243206, -0.6858542, -0.031029783, -0.014595194, -0.011449563, 0.017514233, 0.01743426, 0.009950057, 0.0029706885, -0.015714826, -0.001806072, 0.011856096, 0.026444625, -0.0010663156, -0.006474535, 0.0016161345, -0.020313311, 0.0148351155, -0.0018393943, 0.0057347785, 0.018300641, -0.018647194, 0.03345565, -0.008070676, 0.0071443142, 0.014301958, 0.0044818576, 0.003838736, -0.007350913, -0.024525259, -0.001142124, -0.018620536, 0.017247654, 0.007037683, 0.010236629, 0.06046009, 0.0138887605, -0.012122675, 0.037694257, 0.0055081863, 0.042492677, 0.00021784494, -0.011656162, 0.010276617, 0.022325981, 0.005984696, -0.009496873, 0.013382261, -0.0010563189, 0.0026507939, -0.041639622, 0.008637156, 0.026471283, -0.008403899, 0.024858482, -0.00066686375, -0.0016252982, 0.027590916, 0.0051449724, 0.0058647357, -0.008743787, -0.014968405, 0.027724205, -0.011596181, 0.0047650975, -0.015381602, 0.0043718936, 0.002159289, 0.035908177, -0.008243952, -0.030443309, 0.027564257, 0.042625964, -0.0033688906, 0.01843393, 0.019087048, 0.024578573, 0.03268257, -0.015608194, -0.014128681, -0.0033538956, -0.0028757197, -0.004121976, -0.032389335, 0.0034322033, 0.058807302, 0.010943064, -0.030523283, 0.008903735, 0.017500903, 0.00871713, -0.0029406983, 0.013995391, -0.03132302, -0.019660193, -0.00770413, -0.0038853872, 0.0015894766, -0.0015294964, -0.006251275, -0.021099718, -0.010256623, -0.008863748, 0.028550599, 0.02020668, -0.0012962399, -0.003415542, -0.0022509254, 0.0119360695, 0.027590916, -0.046971202, -0.0015194997, -0.022405956, 0.0016677842, -0.00018535563, -0.015421589, -0.031802863, 0.03814744, 0.0065411795, 0.016567878, -0.015621523, 0.022899127, -0.011076353, 0.02841731, -0.002679118, -0.002342562, 0.015341615, 0.01804739, -0.020566562, -0.012989056, -0.002990682, 0.01643459, 0.00042527664, 0.008243952, -0.013715484, -0.004835075, -0.009803439, 0.03129636, -0.021432944, 0.0012087687, -0.015741484, -0.0052016205, 0.00080890034, -0.01755422, 0.004811749, -0.017967418, -0.026684547, -0.014128681, 0.0041386373, -0.013742141, -0.010056688, -0.013268964, -0.0110630235, -0.028337335, 0.015981404, -0.00997005, -0.02424535, -0.013968734, -0.028310679, -0.027750863, -0.020699851, 0.02235264, 0.001057985, 0.00081639783, -0.0099367285, 0.013522214, -0.012016043, -0.00086471526, 0.013568865, 0.0019376953, -0.019020405, 0.017460918, -0.023045745, 0.008503866, 0.0064678704, -0.011509543, 0.018727167, -0.003372223, -0.0028690554, -0.0027024434, -0.011902748, -0.012182655, -0.015714826, -0.0098634185, 0.00593138, 0.018753825, 0.0010146659, 0.013029044, 0.0003521757, -0.017620865, 0.04102649, 0.00552818, 0.024485271, -0.009630162, -0.015608194, 0.0006718621, -0.0008418062, 0.012395918, 0.0057980907, 0.016221326, 0.010616505, 0.004838407, -0.012402583, 0.019900113, -0.0034521967, 0.000247002, -0.03153628, 0.0011038032, -0.020819811, 0.016234655, -0.00330058, -0.0032289368, 0.00078973995, -0.021952773, -0.022459272, 0.03118973, 0.03673457, -0.021472929, 0.0072109587, -0.015075036, 0.004855068, -0.0008151483, 0.0069643734, 0.010023367, -0.010276617, -0.023019087, 0.0068244194, -0.0012520878, -0.0015086699, 0.022046074, -0.034148756, -0.0022192693, 0.002427534, -0.0027124402, 0.0060346797, 0.015461575, 0.0137554705, 0.009230294, -0.009583511, 0.032629255, 0.015994733, -0.019167023, -0.009203636, 0.03393549, -0.017274313, -0.012042701, -0.0009930064, 0.026777849, -0.013582194, -0.0027590916, -0.017594207, -0.026804507, -0.0014236979, -0.022032745, 0.0091236625, -0.0042419364, -0.00858384, -0.0033905501, -0.020739838, 0.016821127, 0.022539245, 0.015381602, 0.015141681, 0.028817179, -0.019726837, -0.0051283115, -0.011489551, -0.013208984, -0.0047017853, -0.0072309524, 0.01767418, 0.0025658219, -0.010323267, 0.012609182, -0.028097415, 0.026871152, -0.010276617, 0.021912785, 0.0022542577, 0.005124979, -0.0019710176, 0.004518512, -0.040360045, 0.010969722, -0.0031539614, -0.020366628, -0.025778178, -0.0110030435, -0.016221326, 0.0036587953, 0.016207997, 0.003007343, -0.0032555948, 0.0044052163, -0.022046074, -0.0008822095, -0.009363583, 0.028230704, -0.024538586, 0.0029840174, 0.0016044717, -0.014181997, 0.031349678, -0.014381931, -0.027750863, 0.02613806, 0.0004136138, -0.005748107, -0.01868718, -0.0010138329, 0.0054348772, 0.010703143, -0.003682121, 0.0030856507, -0.004275259, -0.010403241, 0.021113047, -0.022685863, -0.023032416, 0.031429652, 0.001792743, -0.005644808, -0.011842767, -0.04078657, -0.0026874484, 0.06915057, -0.00056939584, -0.013995391, 0.010703143, -0.013728813, -0.022939114, -0.015261642, -0.022485929, 0.016807798, 0.007964044, 0.0144219175, 0.016821127, 0.0076241563, 0.005461535, -0.013248971, 0.015301628, 0.0085171955, -0.004318578, 0.011136333, -0.0059047225, -0.010249958, -0.018207338, 0.024645219, 0.021752838, 0.0007614159, -0.013648839, 0.01111634, -0.010503208, -0.0038487327, -0.008203966, -0.00397869, 0.0029740208, 0.008530525, 0.005261601, 0.01642126, -0.0038753906, -0.013222313, 0.026537929, 0.024671877, -0.043505676, 0.014195326, 0.024778508, 0.0056914594, -0.025951454, 0.017620865, -0.0021359634, 0.008643821, 0.021299653, 0.0041686273, -0.009017031, 0.04044002, 0.024378639, -0.027777521, -0.014208655, 0.0028623908, 0.042119466, 0.005801423, -0.028124074, -0.03129636, 0.022139376, -0.022179363, -0.04067994, 0.013688826, 0.013328944, 0.0046184794, -0.02828402, -0.0063412455, -0.0046184794, -0.011756129, -0.010383247, -0.0018543894, -0.0018593877, -0.00052024535, 0.004815081, 0.014781799, 0.018007403, 0.01306903, -0.020433271, 0.009043689, 0.033189073, -0.006844413, -0.019766824, -0.018767154, 0.00533491, -0.0024575242, 0.018727167, 0.0058080875, -0.013835444, 0.0040719924, 0.004881726, 0.012029372, 0.005664801, 0.03193615, 0.0058047553, 0.002695779, 0.009290274, 0.02361889, 0.017834127, 0.0049017193, -0.0036388019, 0.010776452, -0.019793482, 0.0067777685, -0.014208655, -0.024911797, 0.002385881, 0.0034988478, 0.020899786, -0.0025858153, -0.011849431, 0.033189073, -0.021312982, 0.024965113, -0.014635181, 0.014048708, -0.0035921505, -0.003347231, 0.030869836, -0.0017161017, -0.0061346465, 0.009203636, -0.025165047, 0.0068510775, 0.021499587, 0.013782129, -0.0024475274, -0.0051149824, -0.024445284, 0.006167969, 0.0068844, -0.00076183246, 0.030150073, -0.0055948244, -0.011162991, -0.02057989, -0.009703471, -0.020646535, 0.008004031, 0.0066378145, -0.019900113, -0.012169327, -0.01439526, 0.0044252095, -0.004018677, 0.014621852, -0.025085073, -0.013715484, -0.017980747, 0.0071043274, 0.011456228, -0.01010334, -0.0035321703, -0.03801415, -0.012036037, -0.0028990454, -0.05419549, -0.024058744, -0.024272008, 0.015221654, 0.027964126, 0.03182952, -0.015354944, 0.004855068, 0.011522872, 0.004771762, 0.0027874154, 0.023405626, 0.0004242353, -0.03132302, 0.007057676, 0.008763781, -0.0027057757, 0.023005757, -0.0071176565, -0.005238275, 0.029110415, -0.010989714, 0.013728813, -0.009630162, -0.029137073, -0.0049317093, -0.0008630492, -0.015248313, 0.0043219104, -0.0055681667, -0.013175662, 0.029723546, 0.025098402, 0.012849103, -0.0009996708, 0.03118973, -0.0021709518, 0.0260181, -0.020526575, 0.028097415, -0.016141351, 0.010509873, -0.022965772, 0.002865723, 0.0020493253, 0.0020509914, -0.0041419696, -0.00039695262, 0.017287642, 0.0038987163, 0.014795128, -0.014661839, -0.008950386, 0.004431874, -0.009383577, 0.0012604183, -0.023019087, 0.0029273694, -0.033135757, 0.009176978, -0.011023037, -0.002102641, 0.02663123, -0.03849399, -0.0044152127, 0.0004527676, -0.0026924468, 0.02828402, 0.017727496, 0.035135098, 0.02728435, -0.005348239, -0.001467017, -0.019766824, 0.014715155, 0.011982721, 0.0045651635, 0.023458943, -0.0010046692, -0.0031373003, -0.0006972704, 0.0019043729, -0.018967088, -0.024311995, 0.0011546199, 0.007977373, -0.004755101, -0.010016702, -0.02780418, -0.004688456, 0.013022379, -0.005484861, 0.0017227661, -0.015394931, -0.028763862, -0.026684547, 0.0030589928, -0.018513903, 0.028363993, 0.0044818576, -0.009270281, 0.038920518, -0.016008062, 0.0093902415, 0.004815081, -0.021059733, 0.01451522, -0.0051583014, 0.023765508, -0.017874114, -0.016821127, -0.012522544, -0.0028390652, 0.0040886537, 0.020259995, -0.031216389, -0.014115352, -0.009176978, 0.010303274, 0.020313311, 0.0064112223, -0.02235264, -0.022872468, 0.0052449396, 0.0005723116, 0.0037321046, 0.016807798, -0.018527232, -0.009303603, 0.0024858483, -0.0012662497, -0.007110992, 0.011976057, -0.007790768, -0.042999174, -0.006727785, -0.011829439, 0.007024354, 0.005278262, -0.017740825, -0.0041519664, 0.0085905045, 0.027750863, -0.038387362, 0.024391968, 0.00087721116, 0.010509873, -0.00038508154, -0.006857742, 0.0183273, -0.0037054466, 0.015461575, 0.0017394272, -0.0017944091, 0.014181997, -0.0052682655, 0.009023695, 0.00719763, -0.013522214, 0.0034422, 0.014941746, -0.0016711164, -0.025298337, -0.017634194, 0.0058714002, -0.005321581, 0.017834127, 0.0110630235, -0.03369557, 0.029190388, -0.008943722, 0.009363583, -0.0034222065, -0.026111402, -0.007037683, -0.006561173, 0.02473852, -0.007084334, -0.010110005, -0.008577175, 0.0030439978, -0.022712521, 0.0054582027, -0.0012620845, -0.0011954397, -0.015741484, 0.0129557345, -0.00042111133, 0.00846388, 0.008930393, 0.016487904, 0.010469886, -0.007917393, -0.011762793, -0.0214596, 0.000917198, 0.021672864, 0.010269952, -0.007737452, -0.010243294, -0.0067244526, -0.015488233, -0.021552904, 0.017127695, 0.011109675, 0.038067464, 0.00871713, -0.0025591573, 0.021312982, -0.006237946, 0.034628596, -0.0045251767, 0.008357248, 0.020686522, 0.0010696478, 0.0076708077, 0.03772091, -0.018700508, -0.0020676525, -0.008923728, -0.023298996, 0.018233996, -0.010256623, 0.0017860786, 0.009796774, -0.00897038, -0.01269582, -0.018527232, 0.009190307, -0.02372552, -0.042119466, 0.008097334, -0.0066778013, -0.021046404, 0.0019593548, 0.011083017, -0.0016028056, 0.012662497, -0.000059095124, 0.0071043274, -0.014675168, 0.024831824, -0.053582355, 0.038387362, 0.0005698124, 0.015954746, 0.021552904, 0.031589597, -0.009230294, -0.0006147976, 0.002625802, -0.011749465, -0.034362018, -0.0067844326, -0.018793812, 0.011442899, -0.008743787, 0.017474247, -0.021619547, 0.01831397, -0.009037024, -0.0057247817, -0.02728435, 0.010363255, 0.034415334, -0.024032086, -0.0020126705, -0.0045518344, -0.019353628, -0.018340627, -0.03129636, -0.0034038792, -0.006321252, -0.0016161345, 0.033642255, -0.000056075285, -0.005005019, 0.004571828, -0.0024075406, -0.00010215386, 0.0098634185, 0.1980148, -0.003825407, -0.025191706, 0.035161756, 0.005358236, 0.025111731, 0.023485601, 0.0023342315, -0.011882754, 0.018287312, -0.0068910643, 0.003912045, 0.009243623, -0.001355387, -0.028603915, -0.012802451, -0.030150073, -0.014795128, -0.028630573, -0.0013487226, 0.002667455, 0.00985009, -0.0033972147, -0.021486258, 0.009503538, -0.017847456, 0.013062365, -0.014341944, 0.005078328, 0.025165047, -0.015594865, -0.025924796, -0.0018177348, 0.010996379, -0.02993681, 0.007324255, 0.014475234, -0.028577257, 0.005494857, 0.00011725306, -0.013315615, 0.015941417, 0.009376912, 0.0025158382, 0.008743787, 0.023832154, -0.008084005, -0.014195326, -0.008823762, 0.0033455652, -0.032362677, -0.021552904, -0.0056081535, 0.023298996, -0.025444955, 0.0097301295, 0.009736794, 0.015274971, -0.0012937407, -0.018087378, -0.0039387033, 0.008637156, -0.011189649, -0.00023846315, -0.011582852, 0.0066411467, -0.018220667, 0.0060846633, 0.0376676, -0.002709108, 0.0072776037, 0.0034188742, -0.010249958, -0.0007747449, -0.00795738, -0.022192692, 0.03910712, 0.032122757, 0.023898797, 0.0076241563, -0.007397564, -0.003655463, 0.011442899, -0.014115352, -0.00505167, -0.031163072, 0.030336678, -0.006857742, -0.022259338, 0.004048667, 0.02072651, 0.0030156737, -0.0042119464, 0.00041861215, -0.005731446, 0.011103011, 0.013822115, 0.021512916, 0.009216965, -0.006537847, -0.027057758, -0.04054665, 0.010403241, -0.0056281467, -0.005701456, -0.002709108, -0.00745088, -0.0024841821, 0.009356919, -0.022659205, 0.004061996, -0.013175662, 0.017074378, -0.006141311, -0.014541878, 0.02993681, -0.00028448965, -0.025271678, 0.011689484, -0.014528549, 0.004398552, -0.017274313, 0.0045751603, 0.012455898, 0.004121976, -0.025458284, -0.006744446, 0.011822774, -0.015035049, -0.03257594, 0.014675168, -0.0039187097, 0.019726837, -0.0047251107, 0.0022825818, 0.011829439, 0.005391558, -0.016781142, -0.0058747325, 0.010309938, -0.013049036, 0.01186276, -0.0011246296, 0.0062112883, 0.0028190718, -0.021739509, 0.009883412, -0.0073175905, -0.012715813, -0.017181009, -0.016607866, -0.042492677, -0.0014478565, -0.01794076, 0.012302616, -0.015194997, -0.04433207, -0.020606548, 0.009696807, 0.010303274, -0.01694109, -0.004018677, 0.019353628, -0.001991011, 0.000058938927, 0.010536531, -0.17274313, 0.010143327, 0.014235313, -0.024152048, 0.025684876, -0.0012504216, 0.036601283, -0.003698782, 0.0007310093, 0.004165295, -0.0029157067, 0.017101036, -0.046891227, -0.017460918, 0.022965772, 0.020233337, -0.024072073, 0.017220996, 0.009370248, 0.0010363255, 0.0194336, -0.019606877, 0.01818068, -0.020819811, 0.007410893, 0.0019326969, 0.017887443, 0.006651143, 0.00067394477, -0.011889419, -0.025058415, -0.008543854, 0.021579562, 0.0047484366, 0.014062037, 0.0075508473, -0.009510202, -0.009143656, 0.0046817916, 0.013982063, -0.0027990784, 0.011782787, 0.014541878, -0.015701497, -0.029350337, 0.021979429, 0.01332228, -0.026244693, -0.0123492675, -0.003895384, 0.0071576433, -0.035454992, -0.00046984528, 0.0033522295, 0.039347045, 0.0005119148, 0.00476843, -0.012995721, 0.0024042083, -0.006931051, -0.014461905, -0.0127558, 0.0034555288, -0.0074842023, -0.030256703, -0.007057676, -0.00807734, 0.007804097, -0.006957709, 0.017181009, -0.034575284, -0.008603834, -0.005008351, -0.015834786, 0.02943031, 0.016861115, -0.0050849924, 0.014235313, 0.0051449724, 0.0025924798, -0.0025741523, 0.04289254, -0.002104307, 0.012969063, -0.008310596, 0.00423194, 0.0074975314, 0.0018810473, -0.014248641, -0.024725191, 0.0151016945, -0.017527562, 0.0018727167, 0.0002830318, 0.015168339, 0.0144219175, -0.004048667, -0.004358565, 0.011836103, -0.010343261, -0.005911387, 0.0022825818, 0.0073175905, 0.00403867, 0.013188991, 0.03334902, 0.006111321, 0.008597169, 0.030123414, -0.015474904, 0.0017877447, -0.024551915, 0.013155668, 0.023525586, -0.0255116, 0.017220996, 0.004358565, -0.00934359, 0.0099967085, 0.011162991, 0.03092315, -0.021046404, -0.015514892, 0.0011946067, -0.01816735, 0.010876419, -0.10124666, -0.03550831, 0.0056348112, 0.013942076, 0.005951374, 0.020419942, -0.006857742, -0.020873128, -0.021259667, 0.0137554705, 0.0057880944, -0.029163731, -0.018767154, -0.021392956, 0.030896494, -0.005494857, -0.0027307675, -0.006801094, -0.014821786, 0.021392956, -0.0018110704, -0.0018843795, -0.012362596, -0.0072176233, -0.017194338, -0.018713837, -0.024272008, 0.03801415, 0.00015880188, 0.0044951867, -0.028630573, -0.0014070367, -0.00916365, -0.026537929, -0.009576847, -0.013995391, -0.0077107945, 0.0050016865, 0.00578143, -0.04467862, 0.008363913, 0.010136662, -0.0006268769, -0.006591163, 0.015341615, -0.027377652, -0.00093136, 0.029243704, -0.020886457, -0.01041657, -0.02424535, 0.005291591, -0.02980352, -0.009190307, 0.019460259, -0.0041286405, 0.004801752, 0.0011787785, -0.001257086, -0.011216307, -0.013395589, 0.00088137644, -0.0051616337, 0.03876057, -0.0033455652, 0.00075850025, -0.006951045, -0.0062112883, 0.018140694, -0.006351242, -0.008263946, 0.018154023, -0.012189319, 0.0075508473, -0.044358727, -0.0040153447, 0.0093302615, -0.010636497, 0.032789204, -0.005264933, -0.014235313, -0.018393943, 0.007297597, -0.016114693, 0.015021721, 0.020033404, 0.0137688, 0.0011046362, 0.010616505, -0.0039453674, 0.012109346, 0.021099718, -0.0072842683, -0.019153694, -0.003768759, 0.039320387, -0.006747778, -0.0016852784, 0.018154023, 0.0010963057, -0.015035049, -0.021033075, -0.04345236, 0.017287642, 0.016341286, -0.008610498, 0.00236922, 0.009290274, 0.028950468, -0.014475234, -0.0035654926, 0.015434918, -0.03372223, 0.004501851, -0.012929076, -0.008483873, -0.0044685286, -0.0102233, 0.01615468, 0.0022792495, 0.010876419, -0.0059647025, 0.01895376, -0.0069976957, -0.0042952523, 0.017207667, -0.00036133936, 0.0085905045, 0.008084005, 0.03129636, -0.016994404, -0.014915089, 0.020100048, -0.012009379, -0.006684466, 0.01306903, 0.00015765642, -0.00530492, 0.0005277429, 0.015421589, 0.015528221, 0.032202728, -0.003485519, -0.0014286962, 0.033908837, 0.001367883, 0.010509873, 0.025271678, -0.020993087, 0.019846799, 0.006897729, -0.010216636, -0.00725761, 0.01818068, -0.028443968, -0.011242964, -0.014435247, -0.013688826, 0.006101324, -0.0022509254, 0.013848773, -0.0019077052, 0.017181009, 0.03422873, 0.005324913, -0.0035188415, 0.014128681, -0.004898387, 0.005038341, 0.0012320944, -0.005561502, -0.017847456, 0.0008538855, -0.0047884234, 0.011849431, 0.015421589, -0.013942076, 0.0029790192, -0.013702155, 0.0001199605, -0.024431955, 0.019926772, 0.022179363, -0.016487904, -0.03964028, 0.0050849924, 0.017487574, 0.022792496, 0.0012504216, 0.004048667, -0.00997005, 0.0076041627, -0.014328616, -0.020259995, 0.0005598157, -0.010469886, 0.0016852784, 0.01716768, -0.008990373, -0.001987679, 0.026417969, 0.023792166, 0.0046917885, -0.0071909656, -0.00032051947, -0.023259008, -0.009170313, 0.02071318, -0.03156294, -0.030869836, -0.006324584, 0.013795458, -0.00047151142, 0.016874444, 0.00947688, 0.00985009, -0.029883493, 0.024205362, -0.013522214, -0.015075036, -0.030603256, 0.029270362, 0.010503208, 0.021539574, 0.01743426, -0.023898797, 0.022019416, -0.0068777353, 0.027857494, -0.021259667, 0.0025758184, 0.006197959, 0.006447877, -0.00025200035, -0.004941706, -0.021246338, -0.005504854, -0.008390571, -0.0097301295, 0.027244363, -0.04446536, 0.05216949, 0.010243294, -0.016008062, 0.0122493, -0.0199401, 0.009077012, 0.019753495, 0.006431216, -0.037960835, -0.027377652, 0.016381273, -0.0038620618, 0.022512587, -0.010996379, -0.0015211658, -0.0102233, 0.007071005, 0.008230623, -0.009490209, -0.010083347, 0.024431955, 0.002427534, 0.02828402, 0.0035721571, -0.022192692, -0.011882754, 0.010056688, 0.0011904413, -0.01426197, -0.017500903, -0.00010985966, 0.005591492, -0.0077707744, -0.012049366, 0.011869425, 0.00858384, -0.024698535, -0.030283362, 0.020140035, 0.011949399, -0.013968734, 0.042732596, -0.011649498, -0.011982721, -0.016967745, -0.0060913274, -0.007130985, -0.013109017, -0.009710136 + ])), + 'numCandidates': 150, + 'limit': 10 + } + }, { + '$project': { + '_id': 0, + 'plot': 1, + 'title': 1, + 'score': { + '$meta': 'vectorSearchScore' + } + } + } + ]; + // Runs pipeline + const result = coll.aggregate(agg); + + // Prints results + for await (const doc of result) { + console.log(doc); + } + } finally { + await client.close(); + } +} +run().catch(console.dir); + diff --git a/source/includes/atlas-search.js b/source/includes/atlas-search.js new file mode 100644 index 000000000..49e679331 --- /dev/null +++ b/source/includes/atlas-search.js @@ -0,0 +1,41 @@ +const { MongoClient } = require("mongodb"); + +// Replace the placeholder with your connection string. +const uri = ""; +const client = new MongoClient(uri); + +async function run() { + try { + const database = client.db("sample_mflix"); + const collection = database.collection("movies"); + + // Queries for documents that have a "title" value containing the word "Alabama" + // begin-atlas-search + const pipeline = [ + { + $search: { + index: "default", // Replace with your search index name + text: { + query: "Alabama", + path: "title" + } + } + }, + { + $project: { + title: 1 + } + } + ]; + + const cursor = collection.aggregate(pipeline); + for await (const document of cursor) { + console.log(document); + } + // end-atlas-search + } finally { + await client.close(); + } +} + +run().catch(console.dir); \ No newline at end of file diff --git a/source/includes/connect-guide-note.rst b/source/includes/connect-guide-note.rst index c69db80d1..6e7817314 100644 --- a/source/includes/connect-guide-note.rst +++ b/source/includes/connect-guide-note.rst @@ -2,5 +2,4 @@ You can use this example to connect to an instance of MongoDB and interact with a database that contains sample data. To learn more about connecting to your MongoDB - instance and loading a sample dataset, see the :doc:`Usage Examples - guide `. + instance and loading a sample dataset, see the :ref:`node-get-started` guide. diff --git a/source/includes/connect/connection-targets.js b/source/includes/connect/connection-targets.js new file mode 100644 index 000000000..c71cd9935 --- /dev/null +++ b/source/includes/connect/connection-targets.js @@ -0,0 +1,43 @@ +// start-connection-target-atlas +const { MongoClient, ServerApiVersion } = require("mongodb"); + +// Replace the placeholder with your Atlas connection string +const uri = ""; + +// Creates a MongoClient with a MongoClientOptions object to set the Stable API version +const client = new MongoClient(uri, { + serverApi: { + version: ServerApiVersion.v1, + strict: true, + deprecationErrors: true, + } + } +); + +async function run() { + try { + // Connects the client to the server (optional starting in v4.7) + await client.connect(); + + // Sends a ping to confirm a successful connection + await client.db("admin").command({ ping: 1 }); + console.log("Pinged your deployment. You successfully connected to MongoDB!"); + } finally { + // Ensures that the client will close when you finish/error + await client.close(); + } +} +run().catch(console.dir); +// end-connection-target-atlas + +// start-local-connection-uri +const client = new MongoClient("mongodb://host1:27017"); +// end-local-connection-uri + +// start-localhost +const client = new MongoClient("mongodb://localhost:27017"); +// end-localhost + +// start-replica-set-option +const client = new MongoClient("mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myRs"); +// end-replica-set-option diff --git a/source/includes/crud/chain-cursor-methods.rst b/source/includes/crud/chain-cursor-methods.rst new file mode 100644 index 000000000..716d03511 --- /dev/null +++ b/source/includes/crud/chain-cursor-methods.rst @@ -0,0 +1,6 @@ +.. note:: + + You must chain a cursor method such as ``sort()``, ``limit()``, + ``skip()``, or ``project()`` to a read operation before iterating the cursor. + If you specify a cursor method after iterating the cursor, the setting does + not apply to the read operation. \ No newline at end of file diff --git a/source/includes/crud/example-identical-code.rst b/source/includes/crud/example-identical-code.rst new file mode 100644 index 000000000..028615e0e --- /dev/null +++ b/source/includes/crud/example-identical-code.rst @@ -0,0 +1,4 @@ +.. note:: No TypeScript Specific Features + + The following code example uses JavaScript. There are no TypeScript + specific features of the driver relevant to this use case. \ No newline at end of file diff --git a/source/includes/crud/example-intro.rst b/source/includes/crud/example-intro.rst new file mode 100644 index 000000000..a99b9750c --- /dev/null +++ b/source/includes/crud/example-intro.rst @@ -0,0 +1,10 @@ +.. note:: Example Setup + + This example connects to an instance of MongoDB by using a + connection URI. To learn more about connecting to your MongoDB + instance, see the :ref:`node-connect` guide. This example + also uses the ``movies`` collection in the ``sample_mflix`` database + included in the :atlas:`Atlas sample datasets `. You + can load them into your database on the free tier of MongoDB Atlas by + following the :atlas:`Get Started with Atlas Guide + `. \ No newline at end of file diff --git a/source/includes/databases-collections.js b/source/includes/databases-collections.js new file mode 100644 index 000000000..888c56c57 --- /dev/null +++ b/source/includes/databases-collections.js @@ -0,0 +1,50 @@ +const { MongoClient } = require("mongodb"); + +// Replace the placeholder with your connection string. +const uri = ""; +const client = new MongoClient(uri); + +async function run() { + try { + // Accesses the test_database database + // start-access-database + const database = client.db("test_database"); + // end-access-database + + // Accesses the test_collection collection + // start-access-collection + const collection = database.collection("test_collection"); + // end-access-collection + + // Explicitly creates a collection in the database + // start-create-collection + const createColl = await database.createCollection("example_collection"); + // end-create-collection + + // Retrieves information about each collection in the database + // start-find-collections + const colls = database.listCollections(); + for await (const doc of colls) { + console.log(doc) + } + // end-find-collections + + // Retrieves the name of each collection in the database + // start-find-collection-names + const names = database.listCollections({}, { nameOnly: true }); + for await (const doc of names) { + console.log(doc) + } + // end-find-collection-names + + // Deletes the test_collection collection + // start-delete-collection + const collectionToDelete = database.collection("test_collection"); + await collectionToDelete.drop(); + // end-delete-collection + } finally { + await client.close(); + } +} + +run().catch(console.dir); \ No newline at end of file diff --git a/source/includes/figures/atlas_connection_connect_cluster.png b/source/includes/figures/atlas_connection_connect_cluster.png new file mode 100644 index 000000000..eba1fbc15 Binary files /dev/null and b/source/includes/figures/atlas_connection_connect_cluster.png differ diff --git a/source/includes/figures/atlas_connection_copy_uri_node.png b/source/includes/figures/atlas_connection_copy_uri_node.png new file mode 100644 index 000000000..55975c7cd Binary files /dev/null and b/source/includes/figures/atlas_connection_copy_uri_node.png differ diff --git a/source/includes/fundamentals-sections.rst b/source/includes/fundamentals-sections.rst deleted file mode 100644 index c69210ffc..000000000 --- a/source/includes/fundamentals-sections.rst +++ /dev/null @@ -1,20 +0,0 @@ -Learn how to perform the following tasks using the Node.js driver in the -Fundamentals section: - -- :doc:`Connect to MongoDB ` -- :doc:`Use the {+stable-api+} ` -- :doc:`Authenticate with MongoDB ` -- :doc:`Read from and Write to MongoDB ` -- :doc:`Access Return Values ` -- :doc:`Transform your Data ` -- :doc:`Create and Manage Transactions ` -- :doc:`Run a Database Command ` -- :doc:`Create Indexes to Speed Up Queries ` -- :doc:`Sort Using Collations ` -- :doc:`Log Events in the Driver ` -- :doc:`Monitor Driver Events ` -- :doc:`Store and Retrieve Large Files in MongoDB ` -- :doc:`Encrypt Fields from the Client ` -- :doc:`Create and Query Time Series Collection ` -- :doc:`Specify Type Parameters with TypeScript ` -- :doc:`Specify BSON Serialization Settings ` diff --git a/source/includes/fundamentals/configure.js b/source/includes/fundamentals/configure.js new file mode 100644 index 000000000..d22a23aa0 --- /dev/null +++ b/source/includes/fundamentals/configure.js @@ -0,0 +1,109 @@ +const { MongoClient, ReadPreference } = require('mongodb'); + +// start-client-settings +const clientOptions = { + readPreference: ReadPreference.SECONDARY, + readConcern: { level: "local" }, + writeConcern: { w: 2 }, +}; + +const client = new MongoClient("mongodb://localhost:27017", clientOptions); +// end-client-settings + +async function main() { + await client.connect(); + + // start-client-settings-uri + const uri = "mongodb://localhost:27017/?readPreference=secondary&readConcernLevel=local&w=2"; + const clientWithUri = new MongoClient(uri); + // end-client-settings-uri + + // start-transaction-settings + const transactionOptions = { + readPreference: ReadPreference.PRIMARY, + readConcern: { level: "majority" }, + writeConcern: { w: 1 }, + }; + + const session = client.startSession(); + session.startTransaction(transactionOptions); + // end-transaction-settings + + // Sets read and write settings for the "test_database" database + // start-database-settings + const dbOptions = { + readPreference: ReadPreference.PRIMARY_PREFERRED, + readConcern: { level: "available" }, + writeConcern: { w: "majority" }, + }; + + const db = client.db("test_database", dbOptions); + // end-database-settings + + // Sets read and write settings for the "test_collection" collection + // start-collection-settings + const collOptions = { + readPreference: ReadPreference.SECONDARY_PREFERRED, + readConcern: { level: "available" }, + writeConcern: { w: 0 }, + }; + + const collection = db.collection("test_collection", collOptions); + // end-collection-settings + + // Instructs the library to prefer reads from secondary replica set members + // located in New York, followed by a secondary in San Francisco, and + // lastly fall back to any secondary. + // start-tag-set + const taggedReadPreference = new ReadPreference( + ReadPreference.SECONDARY, + [ + { dc: "ny" }, + { dc: "sf" }, + {} + ] + ); + + const dbWithTags = client.db( + "test_database", + { readPreference: taggedReadPreference } + ); + // end-tag-set + + // Instructs the library to distribute reads between members within 35 milliseconds + // of the closest member's ping time + // start-local-threshold + const clientWithLocalThreshold = new MongoClient("mongodb://localhost:27017", { + replicaSet: "repl0", + readPreference: ReadPreference.SECONDARY_PREFERRED, + localThresholdMS: 35 + }); + // end-local-threshold + + // Create the "souvenirs" collection and specify the French Canadian collation + // start-collection-collation + const db = client.db("db") + db.createCollection("names", { + collation: { locale: "fr_CA" }, + }); + // end-collection-collation + + // Create an index collation on the "souvenirs" collection + // start-index-collation + const coll = db.collection("names"); + coll.createIndex( + { "last_name" : 1 }, + { "collation" : { "locale" : "en_US" } }); + // end-index-collation + + // Apply a collation to an operation + // start-operation-collation + coll.findOneAndUpdate( + { first_name: { $lt: "Gunter" } }, + { $set: { verified: true } }, + { collation: { locale: "de@collation=phonebook" } }, + ); + // end-operation-collation +} + +main().catch(console.error); \ No newline at end of file diff --git a/source/index.txt b/source/index.txt index 7cc4d3878..732470635 100644 --- a/source/index.txt +++ b/source/index.txt @@ -16,19 +16,23 @@ MongoDB Node Driver :titlesonly: :maxdepth: 1 - Quick Start - Quick Reference - What's New - Usage Examples - Fundamentals - Aggregation Tutorials + Get Started + Connect + Databases & Collections + CRUD Operations + Promises + Aggregation + Data Formats + Indexes + Run a Database Command + Atlas Search + Atlas Vector Search + Monitoring and Logging + Security + Reference + TypeScript API Documentation <{+api+}> - FAQ - Connection Troubleshooting Issues & Help - Compatibility - Upgrade - Release Notes View the Source Introduction @@ -38,88 +42,99 @@ 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 ----------- +Databases and Collections +------------------------- -For a list of new features and changes in each version, see the -:ref:`What's New ` section. +Learn how to interact wth MongoDB databases and collections in the +:ref:`` section. -Usage Examples --------------- +Read and Write Data +------------------- -For fully runnable code snippets and explanations for common -methods, see the :doc:`Usage Examples ` section. +Learn how to find, update, and delete data in the :ref:`` section. -Fundamentals +Transform Your Data with Aggregation +------------------------------------- + +Learn how to use the {+driver-short+} to perform aggregation operations in the +:ref:`` section. + +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 ---- +Atlas Search +------------ -For answers to commonly asked questions about the MongoDB -Node.js Driver, see the :doc:`Frequently Asked Questions (FAQ) ` -section. +Learn how to run Atlas Search queries in the :ref:`` section. -Connection Troubleshooting --------------------------- +Atlas Vector Search +------------------- -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 how to run Atlas Vector Search queries in the :ref:`` section. -Issues & Help -------------- +Monitoring and Logging +---------------------- -Learn how to report bugs, contribute to the driver, and to find help in the -:doc:`Issues & Help ` section. +Learn how to monitor changes to your application and write them to logs in the +:ref:`` section. -Compatibility -------------- +Secure Your Data +---------------- -For the compatibility tables that show the recommended {+driver-short+} -version for each {+mdb-server+} version, see the -:doc:`Compatibility ` section. +Learn about ways you can authenticate your application and encrypt your data in +the :ref:`` section. -Upgrade Driver Versions ------------------------ +Reference +--------- -Learn what changes you must make to your application to upgrade -driver versions in the :ref:`` section. +Find more information about {+driver-short+} versions, compatibility, and third-party tools in the +:doc:`Reference ` section. + +API Documentation +----------------- + +For detailed information about classes and methods in the MongoDB +Node.js driver, see the `{+driver-long+} API documentation +<{+api+}>`__. + +Issues & Help +------------- + +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 85% rename from source/fundamentals/indexes.txt rename to source/indexes.txt index a01303115..4897e5d01 100644 --- a/source/fundamentals/indexes.txt +++ b/source/indexes.txt @@ -1,8 +1,9 @@ .. _node-fundamentals-indexes: +.. _node-indexes: -======= -Indexes -======= +====================== +Indexes on Collections +====================== .. facet:: :name: genre @@ -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 @@ -339,27 +340,27 @@ To learn more, see :manual:`Unique Indexes `. .. _node-indexes-search: -Search Indexes --------------- +Atlas Search and Atlas Vector Search Indexes +-------------------------------------------- -Atlas Search is a feature that allows you to perform full-text -searches. To learn more, see the :ref:`Atlas Search ` -documentation. +You can programmatically manage your Atlas Search and Atlas Vector +Search indexes by using the {+driver-short+}. -Before you can perform a search on an Atlas collection, you must first -create an Atlas Search index on the collection. An Atlas Search -index is a data structure that categorizes data in a searchable format. +The Atlas Search feature enables you to perform full-text searches on +collections hosted on MongoDB Atlas. To learn more about Atlas +Search, see the :atlas:`Atlas Search +` documentation. -You can use the following methods to manage your Search indexes: +Atlas Vector Search enables you to perform semantic searches on vector +embeddings stored in Atlas. To learn more about Atlas +Vector Search, see the :atlas:`Atlas Vector Search +` documentation. -- ``createSearchIndex()`` -- ``createSearchIndexes()`` -- ``listSearchIndexes()`` -- ``updateSearchIndex()`` -- ``dropSearchIndex()`` +To learn more about how to run an Atlas Search or Atlas Vector Search query, see the +:ref:`node-atlas-search` or :ref:`node-atlas-vector-search` guide. -The following sections provide code samples that use each of the preceding -methods to manage Search indexes. +The following sections contain code examples that demonstrate how to manage Atlas +Search and Atlas Vector Search indexes. Create a Search Index ~~~~~~~~~~~~~~~~~~~~~ @@ -367,10 +368,10 @@ Create a Search Index You can use the `createSearchIndex() <{+api+}/classes/Collection.html#createSearchIndex>`__ and `createSearchIndexes() <{+api+}/classes/Collection.html#createSearchIndexes>`__ -methods to create new Search indexes. +methods to create new Atlas Search and Atlas Vector Search indexes. The following code shows how to -use the ``createSearchIndex()`` method to create an index called +use the ``createSearchIndex()`` method to create an Atlas Search index called ``search1``: .. literalinclude:: /code-snippets/indexes/searchIndexes.js @@ -379,15 +380,12 @@ use the ``createSearchIndex()`` method to create an index called :start-after: start createSearchIndex example :end-before: end createSearchIndex example -When connecting to {+mdb-server+} v6.0.11 and later v6 versions, or -v7.0.2 and later v7 versions, you can use the driver to create an Atlas -Vector Search index on a collection. Learn more about this feature in -the :atlas:`Atlas Vector Search documentation -`. +When connecting to {+mdb-server+} v6.0.11 and later, you can use the driver to +create an Atlas Vector Search index by specifying ``vectorSearch`` in the ``type`` +field of the index definition. The following code shows how to use the ``createSearchIndex()`` method -to create a search index in which the ``type`` field is -``vectorSearch``: +to create an Atlas Vector Search index: .. literalinclude:: /code-snippets/indexes/searchIndexes.js :language: javascript @@ -400,13 +398,14 @@ List Search Indexes You can use the `listSearchIndexes() <{+api+}/classes/Collection.html#listSearchIndexes>`__ -method to return a cursor that contains the Search indexes of a given -collection. The ``listSearchIndexes()`` method takes an optional string -parameter, ``name``, to return only the indexes with matching names. It -also takes an optional `aggregateOptions <{+api+}/interfaces/AggregateOptions.html>`__ parameter. +method to return a cursor that contains the Atlas Search and Atlas Vector Search +indexes of a given collection. The ``listSearchIndexes()`` method takes an +optional string parameter, ``name``, to return only the indexes with matching +names. It also takes an optional +`aggregateOptions <{+api+}/interfaces/AggregateOptions.html>`__ parameter. The following code uses the ``listSearchIndexes()`` method to list the -Search indexes in a collection: +Atlas Search and Atlas Vector Search indexes in a collection: .. literalinclude:: /code-snippets/indexes/searchIndexes.js :language: javascript @@ -418,12 +417,12 @@ Update a Search Index ~~~~~~~~~~~~~~~~~~~~~ You can use the `updateSearchIndex() -<{+api+}/classes/Collection.html#updateSearchIndex>`__ method to update a Search -index. +<{+api+}/classes/Collection.html#updateSearchIndex>`__ method to update an +Atlas Search or Atlas Vector Search index by providing a new index definition. -The following code shows how to -use the ``updateSearchIndex()`` method to update an index called -``search1`` to specify a string type for the ``description`` field: +The following code shows how to use the ``updateSearchIndex()`` method to +update an Atlas Search index called ``search1`` to change the type of the +``description`` field to a string: .. literalinclude:: /code-snippets/indexes/searchIndexes.js :language: javascript @@ -435,12 +434,11 @@ Drop a Search Index ~~~~~~~~~~~~~~~~~~~ You can use the `dropSearchIndex() -<{+api+}/classes/Collection.html#dropSearchIndex>`__ method to remove a Search -index. +<{+api+}/classes/Collection.html#dropSearchIndex>`__ method to remove an Atlas +Search or Atlas Vector Search index. -The following code shows how to -use the ``dropSearchIndex()`` method to remove an index called -``search1``: +The following code shows how to use the ``dropSearchIndex()`` method to remove +an index called ``search1``: .. literalinclude:: /code-snippets/indexes/searchIndexes.js :language: javascript diff --git a/source/monitoring-and-logging.txt b/source/monitoring-and-logging.txt new file mode 100644 index 000000000..9dc894729 --- /dev/null +++ b/source/monitoring-and-logging.txt @@ -0,0 +1,25 @@ +.. _node-monitoring-logging: + +====================== +Monitoring and Logging +====================== + +.. meta:: + :keywords: event + :description: Learn how to monitor and log events by using the {+driver-long+}. + +.. toctree:: + + Monitoring + Logging + Change Streams + +Overview +-------- + +Learn how to set up monitoring and logging for your application in the following +sections: + +- :doc:`/monitoring-and-logging/monitoring` +- :doc:`/monitoring-and-logging/logging` +- :doc:`/monitoring-and-logging/change-streams` \ No newline at end of file diff --git a/source/usage-examples/changeStream.txt b/source/monitoring-and-logging/change-streams.txt similarity index 84% rename from source/usage-examples/changeStream.txt rename to source/monitoring-and-logging/change-streams.txt index 7d72a9479..baeb054da 100644 --- a/source/usage-examples/changeStream.txt +++ b/source/monitoring-and-logging/change-streams.txt @@ -1,14 +1,36 @@ +.. _node-change-streams: .. _node-usage-watch: -================= -Watch for Changes -================= +================================ +Monitor Data with Change Streams +================================ .. 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 -------------------- @@ -73,7 +95,7 @@ read events from the change stream: You can attach listener functions to the ``ChangeStream`` object by calling the ``on()`` method. This method is inherited from the - Javascript ``EventEmitter`` class. Pass the string ``"change"`` as + JavaScript ``EventEmitter`` class. Pass the string ``"change"`` as the first parameter and your listener function as the second parameter as shown below: .. code-block:: javascript @@ -95,37 +117,24 @@ read events from the change stream: .. include:: /includes/changestream-paradigm-warning.rst +.. _node-usage-watch: + Examples -------- Iteration ~~~~~~~~~ -The following example opens a change stream on the ``haikus`` collection in -the ``insertDB`` database and prints change events as they occur: - .. include:: /includes/connect-guide-note.rst -.. tabs:: +.. include:: /includes/crud/example-identical-code.rst - .. tab:: JavaScript - :tabid: javascript - - .. literalinclude:: /code-snippets/usage-examples/changeStream.js - :language: javascript - :linenos: - - .. tab:: TypeScript - :tabid: typescript - - .. literalinclude:: /code-snippets/usage-examples/changeStream.js - :language: javascript - :linenos: - -.. note:: Identical Code Snippets +The following example opens a change stream on the ``haikus`` collection in +the ``insertDB`` database and prints change events as they occur: - The JavaScript and TypeScript code snippets above are identical. There are no - TypeScript specific features of the driver relevant to this use case. +.. literalinclude:: /code-snippets/usage-examples/changeStream.js + :language: javascript + :linenos: When you run this code and then make a change to the ``haikus`` collection, such as performing an insert or delete operation, you can @@ -197,26 +206,11 @@ closing the ``ChangeStream`` instance using the ``close()`` method. the listener and have the listener process the change event before exiting. -.. tabs:: - - .. tab:: JavaScript - :tabid: javascript - - .. literalinclude:: /code-snippets/usage-examples/changeStream_listener.js - :language: javascript - :linenos: - - .. tab:: TypeScript - :tabid: typescript - - .. literalinclude:: /code-snippets/usage-examples/changeStream_listener.js - :language: javascript - :linenos: - -.. note:: Identical Code Snippets +.. include:: /includes/crud/example-identical-code.rst - The JavaScript and TypeScript code snippets above are identical. There are no - TypeScript specific features of the driver relevant to this use case. +.. literalinclude:: /code-snippets/usage-examples/changeStream_listener.js + :language: javascript + :linenos: Visit the following resources for more material on the classes and methods mentioned on this page: diff --git a/source/fundamentals/logging.txt b/source/monitoring-and-logging/logging.txt similarity index 96% rename from source/fundamentals/logging.txt rename to source/monitoring-and-logging/logging.txt index e2cde5919..383e3b70f 100644 --- a/source/fundamentals/logging.txt +++ b/source/monitoring-and-logging/logging.txt @@ -202,18 +202,13 @@ The following example sets the maximum document length to 500 characters: Additional Information ---------------------- -For more information about monitoring with the {+driver-short+}, see the -following monitoring guides: - -- :ref:`Command Monitoring ` -- :ref:`Cluster Monitoring ` -- :ref:`Connection Pool Monitoring ` +For more information about monitoring with the {+driver-short+}, see the :ref:`Monitoring ` guide. API Documentation ~~~~~~~~~~~~~~~~~ To learn more about any of the options or types discussed in this guide, see the -following API documentaion: +following API documentation: - `MongoClientOptions <{+api+}/interfaces/MongoClientOptions.html>`__ - `mongodbLogComponentSeverities <{+api+}/interfaces/MongoClientOptions.html#mongodbLogComponentSeverities>`__ diff --git a/source/monitoring-and-logging/monitoring.txt b/source/monitoring-and-logging/monitoring.txt new file mode 100644 index 000000000..742e4034d --- /dev/null +++ b/source/monitoring-and-logging/monitoring.txt @@ -0,0 +1,739 @@ +.. _node-monitoring: + +========================== +Monitor Application Events +========================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 3 + :class: singlecol + +.. meta:: + :description: Explore cluster, command, and connection pool monitoring in the MongoDB Node.js Driver. + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: event + :description: Learn how to monitor events by using the {+driver-long+}. + +Overview +-------- + +In this guide, you can learn how to set up and configure **monitoring** in the +{+driver-long+}. + +Monitoring involves collecting information about the activities of a running +program, which you can use with an application performance management +library. + +Monitoring the {+driver-short+} lets you understand the driver's resource usage +and performance, and can help you make informed decisions when designing and +debugging your application. + +In this guide you will learn how to perform these tasks: + +- :ref:`Monitor Command Events ` +- :ref:`Monitor Server Discovery and Monitoring (SDAM) Events ` +- :ref:`Monitor Connection Pool Events ` + +This guide shows how to use information about the activity of the driver in code. +To learn how to record events in the driver, see the {+driver-short+}'s +:ref:`Logging ` guide. + +.. _node-monitoring-events: + +Monitor Events +-------------- + +You can monitor events using the {+driver-short+} by subscribing to them in your +application. + +An event is any action that occurs within the driver during its operation. The +{+driver-short+} includes functionality for listening to a subset of these +events. + +The {+driver-short+} organizes the events it defines into the following categories: + +- Command Events +- Server Discovery and Monitoring (SDAM) Events +- Connection Pool Events + +The following sections show how to monitor each event category. + +.. _node-command-monitoring: + +Command Events +~~~~~~~~~~~~~~ + +A command event is an event related to a MongoDB database command. You can +access one or more command monitoring events using the driver by subscribing to +them in your application. + +To learn more about MongoDB database commands, see the +:manual:`Database Commands ` guide in the Server Manual. + +.. note:: + + Command monitoring is disabled by default. To enable command + monitoring, pass the ``monitorCommands`` option as ``true`` to + your ``MongoClient`` constructor. + +Example +``````` + +The following example demonstrates connecting to a replica set and subscribing +to one of the command monitoring events created by the MongoDB deployment: + +.. literalinclude:: /code-snippets/monitoring/apm-subscribe.js + :language: javascript + +Event Descriptions +`````````````````` + +You can subscribe to any of the following command monitoring events: + +.. list-table:: + :widths: 33 67 + :header-rows: 1 + + * - Event Name + - Description + + * - ``commandStarted`` + - Created when a command is started. + + * - ``commandSucceeded`` + - Created when a command succeeded. + + * - ``commandFailed`` + - Created when a command failed. + +commandStarted +++++++++++++++ + +.. code-block:: javascript + :copyable: false + + CommandStartedEvent { + requestId: 1534, + databaseName: "app", + commandName: "find", + address: 'localhost:27017', + connectionId: 812613, + command: { + find: { firstName: "Jane", lastName: "Doe" } + } + } + +commandSucceeded +++++++++++++++++ + +.. code-block:: javascript + :copyable: false + + CommandSucceededEvent { + requestId: 1534, + commandName: "find", + address: 'localhost:27017', + connectionId: 812613, + duration: 15, + reply: { + cursor: { + firstBatch: [ + { + _id: ObjectId("5e8e2ca217b5324fa9847435"), + firstName: "Jane", + lastName: "Doe" + } + ], + _id: 0, + ns: "app.users" + }, + ok: 1, + operationTime: 1586380205 + } + } + + +commandFailed ++++++++++++++ + +.. code-block:: javascript + :copyable: false + + CommandFailedEvent { + requestId: 1534, + commandName: "find", + address: 'localhost:27017', + connectionId: 812613, + failure: Error("something failed"), + duration: 11 + } + + +.. _node-cluster-monitoring: + +Server Discovery and Monitoring Events +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The {+driver-short+} creates topology events, also known as SDAM events, when +there is a change in the state of the instance or cluster that you connected to. +For example, the driver creates an event when you establish a new connection or +if the cluster elects a new primary node. + +To learn more about topology events, see the :manual:`Replication ` guide in the Server Manual. + +The following sections demonstrate how to record topology changes in your application +and explore the information provided in these events. + +Event Subscription Example +`````````````````````````` + +You can access one or more SDAM events by subscribing to them +in your application. The following example demonstrates connecting to a +replica set and subscribing to one of the SDAM events created by the MongoDB +deployment: + +.. literalinclude:: /code-snippets/monitoring/sdam-subscribe.js + :language: javascript + +Event Descriptions +`````````````````` + +You can subscribe to any of the following SDAM events: + +.. list-table:: + :widths: 33 67 + :header-rows: 1 + + * - Event Name + - Description + + * - ``serverOpening`` + - Created when a connection to an instance opens. + + * - ``serverClosed`` + - Created when a connection to an instance closes. + + * - ``serverDescriptionChanged`` + - Created when an instance state changes (such as from secondary to + primary). + + * - ``topologyOpening`` + - Created before attempting a connection to an instance. + + * - ``topologyClosed`` + - Created after all instance connections in the topology close. + + * - ``topologyDescriptionChanged`` + - Created when the topology changes, such as an election of a new + primary or a **mongos** proxy disconnecting. + + * - ``serverHeartbeatStarted`` + - Created before issuing a ``hello`` command to a MongoDB instance. + + * - ``serverHeartbeatSucceeded`` + - Created when the ``hello`` command returns successfully from a + MongoDB instance. + + * - ``serverHeartbeatFailed`` + - Created when a ``hello`` command issued to a specific MongoDB + instance fails to return a successful response. + +Example Event Documents +``````````````````````` + +The following sections show sample output for each type of SDAM event. + +serverDescriptionChanged +++++++++++++++++++++++++ + +.. code-block:: javascript + :copyable: false + + ServerDescriptionChangedEvent { + topologyId: 0, + address: 'localhost:27017', + previousDescription: ServerDescription { + address: 'localhost:27017', + error: null, + roundTripTime: 0, + lastUpdateTime: 1571251089030, + lastWriteDate: null, + opTime: null, + type: 'Unknown', + minWireVersion: 0, + maxWireVersion: 0, + hosts: [], + passives: [], + arbiters: [], + tags: [] + }, + newDescription: ServerDescription { + address: 'localhost:27017', + error: null, + roundTripTime: 0, + lastUpdateTime: 1571251089051, + lastWriteDate: 2019-10-16T18:38:07.000Z, + opTime: { ts: Timestamp, t: 18 }, + type: 'RSPrimary', + minWireVersion: 0, + maxWireVersion: 7, + maxBsonObjectSize: 16777216, + maxMessageSizeBytes: 48000000, + maxWriteBatchSize: 100000, + me: 'localhost:27017', + hosts: [ 'localhost:27017' ], + passives: [], + arbiters: [], + tags: [], + setName: 'rs', + setVersion: 1, + electionId: ObjectID, + primary: 'localhost:27017', + logicalSessionTimeoutMinutes: 30, + '$clusterTime': ClusterTime + } + } + +The ``type`` field of the ``ServerDescription`` object in this event contains +one of the following possible values: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Type + - Description + * - ``Unknown`` + - Unknown instance + * - ``Standalone`` + - Standalone instance + * - ``Mongos`` + - Mongos proxy instance + * - ``PossiblePrimary`` + - At least one server recognizes this as the primary, but is not yet + verified by all instances. + * - ``RSPrimary`` + - Primary instance + * - ``RSSecondary`` + - Secondary instance + * - ``RSArbiter`` + - Arbiter instance + * - ``RSOther`` + - See the `RSGhost and RSOther specification `__ + for more details + * - ``RSGhost`` + - See the `RSGhost and RSOther specification `__ + for more details + +serverHeartbeatStarted +++++++++++++++++++++++ + +.. code-block:: javascript + :copyable: false + + ServerHeartbeatStartedEvent { + connectionId: 'localhost:27017' + } + +serverHeartbeatSucceeded +++++++++++++++++++++++++ + +.. code-block:: javascript + :copyable: false + + ServerHeartbeatSucceededEvent { + duration: 1.939997, + reply:{ + hosts: [ 'localhost:27017' ], + setName: 'rs', + setVersion: 1, + isWritablePrimary: true, + secondary: false, + primary: 'localhost:27017', + me: 'localhost:27017', + electionId: ObjectID, + lastWrite: { + opTime: { ts: [Timestamp], t: 18 }, + lastWriteDate: 2019-10-16T18:38:17.000Z, + majorityOpTime: { ts: [Timestamp], t: 18 }, + majorityWriteDate: 2019-10-16T18:38:17.000Z + }, + maxBsonObjectSize: 16777216, + maxMessageSizeBytes: 48000000, + maxWriteBatchSize: 100000, + localTime: 2019-10-16T18:38:19.589Z, + logicalSessionTimeoutMinutes: 30, + minWireVersion: 0, + maxWireVersion: 7, + readOnly: false, + ok: 1, + operationTime: Timestamp, + '$clusterTime': ClusterTime + }, + connectionId: 'localhost:27017' + } + +serverHeartbeatFailed ++++++++++++++++++++++ + +.. code-block:: javascript + :copyable: false + + ServerHeartbeatFailed { + duration: 20, + failure: MongoError('some error'), + connectionId: 'localhost:27017' + } + +serverOpening ++++++++++++++ + +.. code-block:: javascript + :copyable: false + + ServerOpeningEvent { + topologyId: 0, + address: 'localhost:27017' + } + +serverClosed +++++++++++++ + +.. code-block:: javascript + :copyable: false + + ServerClosedEvent { + topologyId: 0, + address: 'localhost:27017' + } + +topologyOpening ++++++++++++++++ + +.. code-block:: javascript + :copyable: false + + TopologyOpeningEvent { + topologyId: 0 + } + +topologyClosed +++++++++++++++ + +.. code-block:: javascript + :copyable: false + + TopologyClosedEvent { + topologyId: 0 + } + +topologyDescriptionChanged +++++++++++++++++++++++++++ + +.. code-block:: javascript + :copyable: false + + TopologyDescriptionChangedEvent { + topologyId: 0, + previousDescription: TopologyDescription { + type: 'ReplicaSetNoPrimary', + setName: null, + maxSetVersion: null, + maxElectionId: null, + servers: Map { + 'localhost:27017' => ServerDescription + }, + stale: false, + compatible: true, + compatibilityError: null, + logicalSessionTimeoutMinutes: null, + heartbeatFrequencyMS: 10000, + localThresholdMS: 15, + options: Object, + error: undefined, + commonWireVersion: null + }, + newDescription: TopologyDescription { + type: 'ReplicaSetWithPrimary', + setName: 'rs', + maxSetVersion: 1, + maxElectionId: null, + servers: Map { + 'localhost:27017' => ServerDescription + }, + stale: false, + compatible: true, + compatibilityError: null, + logicalSessionTimeoutMinutes: 30, + heartbeatFrequencyMS: 10000, + localThresholdMS: 15, + options: Object, + error: undefined, + commonWireVersion: 7 + } + } + +The ``type`` field of the ``TopologyDescription`` object in this event contains +one of the following possible values: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Type + - Description + + * - ``Single`` + - Standalone instance + + * - ``ReplicaSetWithPrimary`` + - Replica set with a primary + + * - ``ReplicaSetNoPrimary`` + - Replica set with no primary + + * - ``Sharded`` + - Sharded cluster + + * - ``Unknown`` + - Unknown topology + +.. _node-connection-pool-monitoring: + +Connection Pool Events +~~~~~~~~~~~~~~~~~~~~~~ + +A connection pool is a set of open TCP connections your driver maintains with a +MongoDB instance. Connection pools help reduce the number of network handshakes +your application needs to perform and can help your application run faster. + +The following sections demonstrate how to record connection pool events in your +application and explore the information provided in these events. + +Event Subscription Examples +``````````````````````````` + +You can access one or more connection pool events using the driver by +subscribing to them in your application. The following example demonstrates +connecting to a replica set and subscribing to one of the connection +pool monitoring events created by the MongoDB deployment: + +.. literalinclude:: /code-snippets/monitoring/cpm-subscribe.js + :language: javascript + +Connection pool monitoring events can aid you in debugging and understanding +the behavior of your application's connection pool. The following example uses connection +pool monitoring events to return a count of checked-out connections in the pool: + +.. literalinclude:: /code-snippets/monitoring/cpm-status.js + :language: javascript + +Event Descriptions +`````````````````` + +You can subscribe to any of the following connection pool monitoring events: + +.. list-table:: + :widths: 33 67 + :header-rows: 1 + + * - Event Name + - Description + + * - ``connectionPoolCreated`` + - Created when a connection pool is created. + + * - ``connectionPoolReady`` + - Created when a connection pool is ready. + + * - ``connectionPoolClosed`` + - Created when a connection pool is closed before server + instance destruction. + + * - ``connectionCreated`` + - Created when a connection is created, but not necessarily + when it is used for an operation. + + * - ``connectionReady`` + - Created after a connection has successfully completed a + handshake and is ready to be used for operations. + + * - ``connectionClosed`` + - Created when a connection is closed. + + * - ``connectionCheckOutStarted`` + - Created when an operation attempts to acquire a connection for + execution. + + * - ``connectionCheckOutFailed`` + - Created when an operation fails to acquire a connection for + execution. + + * - ``connectionCheckedOut`` + - Created when an operation successfully acquires a connection for + execution. + + * - ``connectionCheckedIn`` + - Created when a connection is checked back into the pool after an operation + is executed. + + * - ``connectionPoolCleared`` + - Created when all connections are closed and the connection pool is + cleared. + +Example Event Documents +``````````````````````` + +The following sections show sample output for each type of connection +pool monitoring event. + +connectionPoolCreated ++++++++++++++++++++++ + +.. code-block:: javascript + :copyable: false + + ConnectionPoolCreatedEvent { + time: 2023-02-13T15:54:06.944Z, + address: '...', + options: {...} + } + +connectionPoolReady ++++++++++++++++++++ + +.. code-block:: javascript + :copyable: false + + ConnectionPoolReadyEvent { + time: 2023-02-13T15:56:38.440Z, + address: '...' + } + +connectionPoolClosed +++++++++++++++++++++ + +.. code-block:: javascript + :copyable: false + + ConnectionPoolClosedEvent { + time: 2023-02-13T15:56:38.440Z, + address: '...' + } + +connectionCreated ++++++++++++++++++ + +.. code-block:: javascript + :copyable: false + + ConnectionCreatedEvent { + time: 2023-02-13T15:56:38.291Z, + address: '...', + connectionId: 1 + } + +connectionReady ++++++++++++++++ + +.. code-block:: javascript + :copyable: false + + ConnectionReadyEvent { + time: 2023-02-13T15:56:38.291Z, + address: '...', + connectionId: 1, + durationMS: 60 + } + +connectionClosed +++++++++++++++++ + +.. code-block:: javascript + :copyable: false + + ConnectionClosedEvent { + time: 2023-02-13T15:56:38.439Z, + address: '...', + connectionId: 1, + reason: 'poolClosed', + serviceId: undefined + } + +connectionCheckOutStarted ++++++++++++++++++++++++++ + +.. code-block:: javascript + :copyable: false + + ConnectionCheckOutStartedEvent { + time: 2023-02-13T15:56:38.291Z, + address: '...', + } + +connectionCheckOutFailed +++++++++++++++++++++++++ + +.. code-block:: javascript + :copyable: false + + ConnectionCheckOutFailedEvent { + time: 2023-02-13T15:56:38.291Z, + address: '...', + reason: ..., + durationMS: 60 + } + +connectionCheckedOut +++++++++++++++++++++ + +.. code-block:: javascript + :copyable: false + + ConnectionCheckedOutEvent { + time: 2023-02-13T15:54:07.188Z, + address: '...', + connectionId: 1, + durationMS: 60 + } + +connectionCheckedIn ++++++++++++++++++++ + +.. code-block:: javascript + :copyable: false + + ConnectionCheckedInEvent { + time: 2023-02-13T15:54:07.189Z, + address: '...', + connectionId: 1 + } + +connectionPoolCleared ++++++++++++++++++++++ + +.. code-block:: javascript + :copyable: false + + ConnectionPoolClearedEvent { + time: 2023-02-13T15:56:38.439Z, + address: '...', + serviceId: undefined, + interruptInUseConnections: true, + } + +API Documentation +----------------- + +To learn more about any of the options or types discussed in this guide, see the +following API documentation: + +- `MongoClientOptions <{+api+}/interfaces/MongoClientOptions.html>`__ +- `MongoClient <{+api+}/classes/MongoClient.html>`__ \ No newline at end of file diff --git a/source/fundamentals/promises.txt b/source/promises.txt similarity index 95% rename from source/fundamentals/promises.txt rename to source/promises.txt index 933ba6bbd..15275c974 100644 --- a/source/fundamentals/promises.txt +++ b/source/promises.txt @@ -1,8 +1,8 @@ .. _node-promises: -======== -Promises -======== +========================================= +Use Promises with Asynchronous JavaScript +========================================= .. facet:: :name: genre @@ -21,15 +21,15 @@ Promises Overview -------- -The Node.js driver uses the asynchronous Javascript API to communicate with +The Node.js driver uses the asynchronous JavaScript API to communicate with your MongoDB cluster. -Asynchronous Javascript allows you to execute operations without waiting for +Asynchronous JavaScript allows you to execute operations without waiting for the processing thread to become free. This helps prevent your application from becoming unresponsive when executing long-running operations. For more information about asynchronous -Javascript, see the MDN web documentation on -`Asynchronous Javascript `_. +JavaScript, see the MDN web documentation on +`Asynchronous JavaScript `_. This section describes ``Promises`` that you can use with the Node.js driver to access the results of your method calls to your MongoDB cluster. 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/quick-start/connect-to-mongodb.txt b/source/quick-start/connect-to-mongodb.txt deleted file mode 100644 index 45a2eb228..000000000 --- a/source/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/quick-start/create-a-connection-string.txt b/source/quick-start/create-a-connection-string.txt deleted file mode 100644 index cc580776c..000000000 --- a/source/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/quick-start/create-a-deployment.txt b/source/quick-start/create-a-deployment.txt deleted file mode 100644 index a1fade2f2..000000000 --- a/source/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/quick-start/download-and-install.txt b/source/quick-start/download-and-install.txt deleted file mode 100644 index 76c22f2c6..000000000 --- a/source/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/quick-start/facets.toml b/source/quick-start/facets.toml deleted file mode 100644 index 07bd7b7f7..000000000 --- a/source/quick-start/facets.toml +++ /dev/null @@ -1,3 +0,0 @@ -[[facets]] -category = "genre" -value = "tutorial" diff --git a/source/quick-start/next-steps.txt b/source/quick-start/next-steps.txt deleted file mode 100644 index 55d656e6c..000000000 --- a/source/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/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 98% rename from source/whats-new.txt rename to source/reference/release-notes.txt index fa6215295..3cb3474b0 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: @@ -208,8 +209,7 @@ The {+driver-short+} v6.11 release includes the following features: releases. - Adds OIDC authentication support for Kubernetes environments. To learn - more about this feature, see the :ref:`node-enterprise-auth-oidc` - section of the Enterprise Authentication Mechanisms guide. + more about this feature, see the :ref:`node-authentication-oidc` guide. To use OIDC to authenticate from a Kubernetes environment, set the ``authMechanismProperties`` connection option to ``ENVIRONMENT:k8s`` @@ -682,7 +682,7 @@ The {+driver-short+} v6.1 release includes the following features: To learn how to set region settings when using the ``MONGODB-AWS`` authentication mechanism, see the :guilabel:`Web Identity Token` tab in the - :ref:`MONGODB-AWS ` section of the Authentication Mechanisms guide. + :ref:`AWS IAM Authentication Mechanism ` guide. - Fixes a memory leak issue caused by recursive calls to the ``next()`` method of the ``ChangeStream`` type. @@ -763,7 +763,7 @@ The {+driver-short+} v6.0 release includes the following features: Although you cannot pass these options to the ``Db.command()`` method, you can still set them in the command document. To learn more, see the :ref:`Command Options - ` section of the Run a Command guide. + ` section of the Run a Database Command guide. To learn more about this release, see the `v6.0.0 Release Highlights `__. diff --git a/source/upgrade.txt b/source/reference/upgrade.txt similarity index 98% rename from source/upgrade.txt rename to source/reference/upgrade.txt index c8c4d59f1..369385937 100644 --- a/source/upgrade.txt +++ b/source/reference/upgrade.txt @@ -133,8 +133,9 @@ Version 6.0 Breaking Changes callback returns. In previous driver versions, this method returns the server command response, which varies depending on the MongoDB Server version or type that the driver connects to. To learn more - about transactions, see the :ref:`node-usage-txns` usage - examples and the :ref:`nodejs-transactions` guide. + about transactions, see the :ref:`Convenient Transaction API + ` and :ref:`Core API ` guides + and the :ref:`nodejs-transactions` guide. - Raised the optional ``kerberos`` dependency minimum version to 2.0.1 and removed support for version 1.x. - Raised the optional ``zstd`` dependency minimum version to 1.1.0. diff --git a/source/fundamentals/run-command.txt b/source/run-command.txt similarity index 88% rename from source/fundamentals/run-command.txt rename to source/run-command.txt index 4027e6700..322c224ba 100644 --- a/source/fundamentals/run-command.txt +++ b/source/run-command.txt @@ -1,8 +1,8 @@ .. _node-run-command: -============== -Run a Command -============== +====================== +Run a Database Command +====================== .. meta:: :description: Learn how to execute database commands using the MongoDB Node.js Driver, including options and response handling. @@ -13,6 +13,14 @@ Run a Command :depth: 2 :class: singlecol +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: database, call, admin, administration, meta, backend, configure + :description: Learn about how to run database commands in the {+driver-long+}. + Overview -------- @@ -204,6 +212,34 @@ describe any metadata inconsistencies in the database: command result documents when you access the contents of the cursor. You won't see the ``ok``, ``operationTime``, and ``$clusterTime`` fields. +.. _node-run-command-usageex: + +Run Command Example: Full File +------------------------------ + +.. include:: /includes/crud/example-intro.rst + +.. include:: /includes/crud/example-identical-code.rst + +In the following sample code, we send the ``dbStats`` command to request +statistics from the ``sample_mflix`` database: + +.. literalinclude:: /code-snippets/usage-examples/command.js + :language: javascript + :linenos: + +Running the preceding command results in the following output: + +.. code-block:: javascript + :copyable: false + + { + db: 'sample_mflix', + collections: 6, + views: 0, + objects: 75620, + .. + .. _addl-info-runcommand: Additional Information diff --git a/source/security.txt b/source/security.txt new file mode 100644 index 000000000..ccd9ffa2b --- /dev/null +++ b/source/security.txt @@ -0,0 +1,39 @@ +.. _node-security: + +================ +Secure Your Data +================ + +.. 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 +-------- + +Learn how to set up security and authentication for your application +in the following sections: + +- :ref:`Authentication ` +- :ref:`In-Use Encryption ` +- :ref:`TLS Security Protocol ` +- :ref:`SOCKS Proxy ` diff --git a/source/security/authentication.txt b/source/security/authentication.txt new file mode 100644 index 000000000..f6906c2fa --- /dev/null +++ b/source/security/authentication.txt @@ -0,0 +1,73 @@ +.. _node-authentication-mechanisms: +.. _node-authentication: + +========================= +Authentication Mechanisms +========================= + +.. meta:: + :description: Authenticate using the MongoDB Node.js Driver with various supported authentication mechanisms. + +.. default-domain:: mongodb + +.. toctree:: + + SCRAM + X.509 + AWS IAM + OIDC + LDAP (PLAIN) + Kerberos (GSSAPI) + +Overview +-------- + +In this guide, you can learn how to authenticate to MongoDB by using the +**authentication mechanisms** available in {+mdb-server+}. +Authentication mechanisms are processes by which the driver and server confirm +the identity of a client to ensure security before connecting. + +.. tip:: Connecting to MongoDB + + To learn how to establish a connection to your MongoDB deployment, see the + :ref:`node-connect` guide. + +MongoDB Edition Compatibility +----------------------------- + +The following table lists the authentication mechanisms supported by MongoDB and +the {+mdb-server+} editions that each mechanism is compatible with. Click the name of +a mechanism to learn more about how to use it with your application. + +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + + * - Authentication Mechanism + - Atlas + - Enterprise Advanced + - Community + * - :ref:`` + - Yes + - Yes + - Yes + * - :ref:`` + - Yes + - Yes + - Yes + * - :ref:`` + - Yes + - No + - No + * - :ref:`` + - Yes + - Yes + - No + * - :ref:`` + - Yes + - Yes + - No + * - :ref:`` + - No + - Yes + - No diff --git a/source/security/authentication/aws-iam.txt b/source/security/authentication/aws-iam.txt new file mode 100644 index 000000000..0288200c6 --- /dev/null +++ b/source/security/authentication/aws-iam.txt @@ -0,0 +1,186 @@ +.. _node-authentication-aws: + +================================ +AWS IAM Authentication Mechanism +================================ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 3 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: atlas, amazon web services, code example + +Overview +-------- + +The ``MONGODB-AWS`` authentication mechanism uses Amazon Web Services +Identity and Access Management (AWS IAM) credentials to authenticate a user to MongoDB. +You can use this mechanism only when authenticating to MongoDB Atlas. + +.. tip:: Configure Atlas for AWS IAM Authentication + + To learn more about configuring MongoDB Atlas for AWS IAM authentication, see + :atlas:`Set Up Authentication with AWS IAM ` in + the Atlas documentation. + +Specify MONGODB-AWS Authentication +---------------------------------- + +The ``MONGODB-AWS`` authentication mechanism uses your Amazon Web Services +Identity and Access Management (AWS IAM) credentials to authenticate your +user. If you do not already have the `AWS signature library +`__, use the following +``npm`` command to install it: + +.. code-block:: bash + + npm install aws4 + +To connect to a MongoDB instance with ``MONGODB-AWS`` authentication +enabled, specify the ``MONGODB-AWS`` authentication mechanism. + +The driver checks for your credentials in the following sources in order: + +1. Connection string +#. Environment variables +#. Web identity token file +#. AWS ECS endpoint specified in ``AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`` +#. AWS EC2 endpoint. For more information, see `IAM Roles for Tasks + `_. + +.. important:: + + The driver only reads the credentials from the first method that it detects + in the order as given by the preceding list. For example, if you specify + your AWS credentials in the connection string, the driver ignores any + credentials that you specified in environment variables. + +.. tabs:: + + .. tab:: Connection String + :tabid: connection string + + To connect to your MongoDB instance with a connection string, pass + your ``AWS_ACCESS_KEY_ID`` and ``AWS_SECRET_ACCESS_KEY`` + credentials to the driver when you attempt to connect. If your AWS + login requires a session token, include your ``AWS_SESSION_TOKEN`` as well. + + The following code shows an example of specifying the ``MONGODB-AWS`` + authentication mechanism and credentials with a connection string: + + .. important:: + + Always **URI encode** the username and certificate file path using the + ``encodeURIComponent`` method to ensure they are correctly parsed. + + .. literalinclude:: /code-snippets/authentication/aws.js + :language: javascript + + .. tab:: Environment Variables + :tabid: environment variables + + To authenticate to your MongoDB instance using AWS credentials stored in + environment variables, set the following variables by using + a shell: + + .. code-block:: bash + + export AWS_ACCESS_KEY_ID= + export AWS_SECRET_ACCESS_KEY= + export AWS_SESSION_TOKEN= + + .. note:: + + Omit the line containing ``AWS_SESSION_TOKEN`` if you don't need an AWS + session token for that role. + + After you've set the preceding environment variables, specify the ``MONGODB-AWS`` + authentication mechanism in your connection string as shown in the following example: + + .. literalinclude:: /code-snippets/authentication/aws-env-variable.js + :language: javascript + + .. tab:: Web Identity Token File + :tabid: web-identity-token-file + + You can use the OpenID Connect (OIDC) token obtained from a web identity + provider to authenticate to Amazon Elastic Kubernetes Service (EKS) or + other services. + + To authenticate with your OIDC token you must first install + `@aws-sdk/credential-providers + `__. You can + install this dependency using the following ``npm`` command: + + .. code-block:: bash + + npm install @aws-sdk/credential-providers + + Next, create a file that contains your OIDC token. Then + set the absolute path to this file in an environment variable by using + a shell as shown in the following example: + + .. code-block:: bash + + export AWS_WEB_IDENTITY_TOKEN_FILE= + + AWS recommends using regional AWS STS endpoints instead of global + endpoints to reduce latency, build-in redundancy, and increase session token validity. + To set the AWS region, set `AWS_REGION `__ + and `AWS_STS_REGIONAL_ENDPOINTS `__ + as environment variables, as shown in the following example: + + .. code-block:: bash + + export AWS_STS_REGIONAL_ENDPOINTS=regional // Enables regional endpoints + export AWS_REGION=us-east-1 // Sets your AWS region + + If both these environment variables aren't set, the default region is + ``us-east-1``. For a list of available AWS regions, see the + `Regional Endpoints `__ + section of the AWS Service Endpoints reference in the AWS documentation. + + .. warning:: Consult your SDK's Documentation for Setting an AWS Region + + You cannot set your AWS region with environment variables for all SDKs, + as in the above example. See your SDK's specific documentation for + configuring an AWS region. + + After you've set the preceding environment variables, specify the ``MONGODB-AWS`` + authentication mechanism in your connection string as shown in the following example: + + .. literalinclude:: /code-snippets/authentication/aws-env-variable.js + :language: javascript + +.. important:: Retrieval of AWS Credentials + + Starting in MongoDB version 4.11, when you install the optional + ``aws-sdk/credential-providers`` dependency, the driver uses the AWS SDK + to retrieve credentials from the environment. As a result, if you + have a shared AWS credentials file or config file, the driver will + use those credentials by default. + + You can override this behavior by performing one of the following + actions: + + - Set ``AWS_SHARED_CREDENTIALS_FILE`` variable in your shell to point + to your credentials file. + - Set the equivalent environment variable in your application to point + to your credentials file. + - Create an AWS profile for your MongoDB credentials and set the + ``AWS_PROFILE`` environment variable to that profile name. + +API Documentation +----------------- + +To learn more about any of the methods or types discussed on this +page, see the following API documentation: + +- `MongoClient <{+api+}/classes/MongoClient.html>`__ diff --git a/source/security/authentication/kerberos.txt b/source/security/authentication/kerberos.txt new file mode 100644 index 000000000..3b7c98f27 --- /dev/null +++ b/source/security/authentication/kerberos.txt @@ -0,0 +1,114 @@ +.. _node-authentication-kerberos: + +========================================== +Kerberos (GSSAPI) Authentication Mechanism +========================================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example + +Overview +-------- + +The Generic Security Services API (GSSAPI) authentication mechanism allows you to +use your principal name to authenticate to a Kerberos service. +You can use this mechanism only when authenticating to MongoDB Enterprise Advanced. + +Specify Kerberos (GSSAPI) Authentication +---------------------------------------- + +.. note:: + The Node.js driver supports Kerberos on UNIX using the MIT Kerberos library + and on Windows using the SSPI API. + +The ``GSSAPI`` authentication mechanism uses your user principal to +authenticate to a Kerberos service. + +You can specify this authentication mechanism by performing the +following actions while specifying options on your +:manual:`connection string `: + +- Set the ``authMechanism`` parameter to ``GSSAPI``. +- Set the ``SERVICE_NAME`` value in the ``authMechanismProperties`` + parameter if using a value other than ``mongodb``. +- Specify a ``SERVICE_REALM`` value in the ``authMechanismProperties`` + parameter if a custom service realm is required. +- Specify a ``CANONICALIZE_HOST_NAME`` value in the ``authMechanismProperties`` + parameter if canonicalization of the hostname is required. This property accepts + the following values: + + - ``none``: (Default) Does not perform hostname canonicalization + - ``forward``: Performs a forward DNS lookup to canonicalize the hostname + - ``forwardAndReverse``: Performs a forward DNS lookup and then a + reverse lookup on that value to canonicalize the hostname + +.. important:: + + The ``gssapiServiceName`` parameter is deprecated and may be removed + in future versions of the driver. Use + ``authMechanismProperties=SERVICE_NAME:`` in the + connection URI instead. + To learn more about the authentication options for a connection string, see the + :manual:`Authentication Options ` + section of the Connection String Options reference in the Server Manual. + +The following code example authenticates to Kerberos for UNIX using ``GSSAPI``. + +.. important:: + Always **URI encode** the principal using the ``encodeURIComponent`` method + to ensure it is correctly parsed. + +.. code-block:: js + + const { MongoClient } = require("mongodb"); + + // Replace the placeholder values with the values for your environment in the following lines + const clusterUrl = ""; + const principal = encodeURIComponent(""); + const serviceRealm = ""; + const canonicalizationSetting = ""; + const authMechanismProperties = `SERVICE_REALM:${serviceRealm},CANONICALIZE_HOST_NAME:${canonicalizationSetting}`; + + const authMechanism = "GSSAPI"; + + // Connection URI + const uri = `mongodb+srv://${principal}@${clusterUrl}/?authMechanism=${authMechanism}&authMechanismProperties=${authMechanismProperties}`; + + const client = new MongoClient(uri); + + // Function to connect to the server + async function run() { + try { + // Establish and verify connection + await client.db("admin").command({ ping: 1 }); + console.log("Connected successfully to server"); + } finally { + // Ensures that the client will close when you finish/error + await client.close(); + } + } + run().catch(console.dir); + +.. note:: + The method refers to the ``GSSAPI`` authentication mechanism instead + of ``Kerberos`` because the driver authenticates through + `GSSAPI RFC-4652 `_, the SASL + mechanism. + +API Documentation +----------------- + +To learn more about any of the methods or types discussed on this +page, see the following API documentation: + +- `MongoClient <{+api+}/classes/MongoClient.html>`__ diff --git a/source/security/authentication/ldap.txt b/source/security/authentication/ldap.txt new file mode 100644 index 000000000..8d2ec793e --- /dev/null +++ b/source/security/authentication/ldap.txt @@ -0,0 +1,87 @@ +.. _node-authentication-ldap: + +===================================== +LDAP (PLAIN) Authentication Mechanism +===================================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example + +Overview +-------- + +The ``PLAIN`` authentication mechanism allows you to use your Lightweight Directory +Access Protocol (LDAP) username and password to authenticate to MongoDB. LDAP +authentication uses the PLAIN Simple Authentication and Security Layer (SASL) +defined in `RFC-4616 `__. + +You can use this mechanism only when authenticating to MongoDB Atlas or MongoDB +Enterprise Advanced. + +Code Placeholders +~~~~~~~~~~~~~~~~~ + +The code examples on this page use the following placeholders: + +- ````: Your LDAP username. +- ````: Your LDAP password. +- ````: The network address of your MongoDB deployment. + +To use the code examples, replace these placeholders with your own values. + +LDAP (PLAIN) +------------ + +The ``PLAIN`` authentication mechanism uses your username and password to +authenticate to an LDAP server. + +You can specify this authentication mechanism by setting the ``authMechanism`` +parameter to ``PLAIN`` and including your LDAP username and password in the +:manual:`connection string ` as shown +in the following sample code. + +.. code-block:: js + + const { MongoClient } = require("mongodb"); + + // specify the placeholder values for your environment in the following lines + const clusterUrl = ""; + const ldapUsername = ""; + const ldapPassword = ""; + const authMechanism = "PLAIN"; + + // Connection URI + const uri = `mongodb+srv://${ldapUsername}:${ldapPassword}@${clusterUrl}/?authMechanism=${authMechanism}`; + + const client = new MongoClient(uri); + + // Function to connect to the server + async function run() { + try { + // Establish and verify connection + await client.db("admin").command({ ping: 1 }); + console.log("Connected successfully to server"); + } finally { + // Ensures that the client will close when you finish/error + await client.close(); + } + } + run().catch(console.dir); + +API Documentation +----------------- + +To learn more about any of the methods or types discussed on this +page, see the following API documentation: + +- `MongoClient <{+api+}/classes/MongoClient.html>`__ diff --git a/source/fundamentals/authentication/enterprise-mechanisms.txt b/source/security/authentication/oidc.txt similarity index 56% rename from source/fundamentals/authentication/enterprise-mechanisms.txt rename to source/security/authentication/oidc.txt index a233a857d..23f991912 100644 --- a/source/fundamentals/authentication/enterprise-mechanisms.txt +++ b/source/security/authentication/oidc.txt @@ -1,8 +1,8 @@ -.. _node-enterprise-authentication-mechanisms: +.. _node-authentication-oidc: -==================================== -Enterprise Authentication Mechanisms -==================================== +============================= +OIDC Authentication Mechanism +============================= .. contents:: On this page :local: @@ -13,157 +13,39 @@ Enterprise Authentication Mechanisms .. facet:: :name: genre :values: reference - + .. meta:: :keywords: ldap, encryption, principal, tls :description: Explore sample code for connecting to MongoDB using enterprise authentication mechanisms like Kerberos, LDAP, and MONGODB-OIDC with the MongoDB Node.js Driver. -In this guide, you can find sample code for connection to MongoDB with each -authentication mechanism available in the MongoDB Enterprise Edition: -``Kerberos (GSSAPI/SSPI)``, ``LDAP (PLAIN)``, and ``MONGODB-OIDC``. - -Kerberos (GSSAPI/SSPI) ----------------------- - -.. note:: - The Node.js driver supports Kerberos on UNIX using the MIT Kerberos library - and on Windows using the SSPI API. +Overview +-------- -The ``GSSAPI`` authentication mechanism uses your user principal to -authenticate to a Kerberos service. +The OpenID Connect (OIDC) authentication mechanism allows you to authenticate to +MongoDB by using a third-party identity provider, such as Azure or Google Cloud +Platform (GCP). -You can specify this authentication mechanism by performing the -following actions while specifying options on your -:manual:`connection string `: +The MONGODB-OIDC authentication mechanism requires {+mdb-server+} v7.0 or later running +on a Linux platform. You can use this mechanism only when authenticating to MongoDB Atlas +or MongoDB Enterprise Advanced. -- Set the ``authMechanism`` parameter to ``GSSAPI``. -- Set the ``SERVICE_NAME`` value in the ``authMechanismProperties`` - parameter if using a value other than ``mongodb``. -- Specify a ``SERVICE_REALM`` value in the ``authMechanismProperties`` - parameter if a custom service realm is required. -- Specify a ``CANONICALIZE_HOST_NAME`` value in the ``authMechanismProperties`` - parameter if canonicalization of the hostname is required. This property can take - the following values: +.. tip:: Learn More about OIDC Authentication - - ``none``: (Default) Does not perform hostname canonicalization - - ``forward``: Performs a forward DNS lookup to canonicalize the hostname - - ``forwardAndReverse``: Performs a forward DNS lookup and then a - reverse lookup on that value to canonicalize the hostname - -.. important:: + To learn more about configuring MongoDB Atlas for OIDC authentication, see + :atlas:`Set up Workforce Identity Federation with OIDC ` + in the Atlas documentation. - The ``gssapiServiceName`` parameter is deprecated and may be removed - in future versions of the driver. Use - ``authMechanismProperties=SERVICE_NAME:`` in the - connection URI instead. - See the - :manual:`authMechanismProperties ` - parameter documentation for more information. - -The following code sample authenticates to Kerberos for UNIX using ``GSSAPI``. - -.. important:: - Always **URI encode** the principal using the ``encodeURIComponent`` method - to ensure it is correctly parsed. - -.. code-block:: js - - const { MongoClient } = require("mongodb"); - - // specify the placeholder values for your environment in the following lines - const clusterUrl = ""; - const principal = encodeURIComponent(""); - const serviceRealm = ""; - const canonicalizationSetting = ""; - const authMechanismProperties = `SERVICE_REALM:${serviceRealm},CANONICALIZE_HOST_NAME:${canonicalizationSetting}`; - - const authMechanism = "GSSAPI"; - - // Connection URI - const uri = `mongodb+srv://${principal}@${clusterUrl}/?authMechanism=${authMechanism}&authMechanismProperties=${authMechanismProperties}`; - - const client = new MongoClient(uri); - - // Function to connect to the server - async function run() { - try { - // Establish and verify connection - await client.db("admin").command({ ping: 1 }); - console.log("Connected successfully to server"); - } finally { - // Ensures that the client will close when you finish/error - await client.close(); - } - } - run().catch(console.dir); - -.. note:: - The method refers to the ``GSSAPI`` authentication mechanism instead - of ``Kerberos`` because the driver authenticates through - `GSSAPI RFC-4652 `_, the SASL - mechanism. - -LDAP (PLAIN) ------------- - -The ``PLAIN`` authentication mechanism uses your username and password to -authenticate to a Lightweight Directory Access Protocol (LDAP) server. - -You can specify this authentication mechanism by setting the ``authMechanism`` -parameter to ``PLAIN`` and including your LDAP username and password in the -:manual:`connection string ` as shown -in the following sample code. - -.. code-block:: js - - const { MongoClient } = require("mongodb"); - - // specify the placeholder values for your environment in the following lines - const clusterUrl = ""; - const ldapUsername = ""; - const ldapPassword = ""; - const authMechanism = "PLAIN"; - - // Connection URI - const uri = `mongodb+srv://${ldapUsername}:${ldapPassword}@${clusterUrl}/?authMechanism=${authMechanism}`; - - const client = new MongoClient(uri); - - // Function to connect to the server - async function run() { - try { - // Establish and verify connection - await client.db("admin").command({ ping: 1 }); - console.log("Connected successfully to server"); - } finally { - // Ensures that the client will close when you finish/error - await client.close(); - } - } - run().catch(console.dir); - -.. note:: - The authentication mechanism is named ``PLAIN`` instead of ``LDAP`` since it - authenticates using the `PLAIN Simple Authentication and Security Layer - (SASL) defined in RFC-4616 `_. - -.. _node-enterprise-auth-oidc: - -MONGODB-OIDC ------------- - -.. important:: + To learn more about using OIDC authentication with MongoDB, see + :manual:`Authentication and Authorization with OIDC/OAuth 2.0 ` and + :manual:`oidcIdentityProviders ` + in the {+mdb-server+} manual. - The MONGODB-OIDC authentication mechanism requires {+mdb-server+} v7.0 or later running - on a Linux platform. -The following sections describe how to use the MONGODB-OIDC authentication mechanism to -authenticate from various platforms. +Specify OIDC Authentication +--------------------------- -For more information about the MONGODB-OIDC authentication mechanism, see -:manual:`OpenID Connect Authentication ` and -:manual:`MongoDB Server Parameters ` -in the {+mdb-server+} manual. +The following sections describe how to use the ``MONGODB-OIDC`` authentication +mechanism to authenticate from various platforms. .. _node-mongodb-oidc-azure-imds: @@ -197,9 +79,9 @@ The following code example shows how to set the preceding connection options: const uri = "mongodb+srv://@:/?authMechanism=MONGODB-OIDC" + "&authMechanismProperties=ENVIRONMENT:azure,TOKEN_RESOURCE:"; - const client = new MongoClient(uri); + const client = new MongoClient(uri); -.. _node-mongodb-oidc-gcp-imds: +.. _node-mongodb-oidc-gcp-imds: GCP IMDS ~~~~~~~~ @@ -376,4 +258,4 @@ guide, see the following API documentation: - `MongoClient <{+api+}/classes/MongoClient.html>`__ - `OIDCCallbackParams <{+api+}/interfaces/OIDCCallbackParams.html>`__ -- `OIDCResponse <{+api+}/interfaces/OIDCResponse.html>`__ \ No newline at end of file +- `OIDCResponse <{+api+}/interfaces/OIDCResponse.html>`__ diff --git a/source/security/authentication/scram.txt b/source/security/authentication/scram.txt new file mode 100644 index 000000000..979374e6d --- /dev/null +++ b/source/security/authentication/scram.txt @@ -0,0 +1,145 @@ +.. _node-authentication-scram: + +=============================== +SCRAM Authentication Mechanisms +=============================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: salt, default, code example + +Overview +-------- + +**Salted Challenge Response Authentication Mechanism (SCRAM)** is a family of +authentication mechanisms that use a challenge-response mechanism to authenticate +the user. SCRAM-SHA-256, which uses the SHA-256 algorithm to hash your password, is the +default authentication mechanism in {+mdb-server+} version 4.0 +and later. SCRAM-SHA-1, which uses the SHA-1 algorithm instead, is the default +authentication mechanism in {+mdb-server+} versions earlier than 4.0. + +You can use SCRAM to authenticate to MongoDB Atlas, MongoDB +Enterprise Advanced, and MongoDB Community Edition. + +.. tip:: SCRAM Mechanisms + + To learn more about the SCRAM family of authentication mechanisms, see + `RFC 5802 `__ and + :wikipedia:`Salted Challenge Response Authentication Mechanism ` + on Wikipedia. + + For more information about the MongoDB implementation of SCRAM, see + :manual:`SCRAM ` in the {+mdb-server+} manual. + +Code Placeholders +~~~~~~~~~~~~~~~~~ + +The code examples on this page use the following placeholders: + +- ````: The MongoDB username of the user to authenticate. +- ````: The MongoDB password of the user to authenticate. +- ````: The network address of your MongoDB deployment. + +To use the code examples, replace these placeholders with your own values. + +Default Authentication Mechanism +-------------------------------- + +The ``DEFAULT`` authentication mechanism is a fallback setting that instructs +the driver to negotiate the first authentication mechanism supported by the +server in the following order of preference: + +#. ``SCRAM-SHA-256`` +#. ``SCRAM-SHA-1`` +#. ``MONGODB-CR`` + +If the ``DEFAULT`` option is specified, the driver first attempts to +authenticate using ``SCRAM-SHA-256``. If the version of the MongoDB instance +does not support that mechanism, the driver attempts to authenticate using +``SCRAM-SHA-1``. If the instance does not support that mechanism either, +the driver attempts to authenticate using ``MONGODB-CR``. + +You can specify the default authentication mechanism by setting the +``authMechanism`` parameter to ``DEFAULT`` in the connection string, or by +omitting the parameter since it is the default value. + +The following example shows how to set the authentication mechanism to the +default by setting ``authMechanism`` to ``DEFAULT`` in the connection string: + +.. important:: + Always **URI encode** the username and password using the + ``encodeURIComponent`` method to ensure they are correctly parsed. + +.. literalinclude:: /code-snippets/authentication/default.js + :language: javascript + +To learn more about the SCRAM version that MongoDB supports, +see the :manual:`SCRAM ` section of the {+mdb-server+} +manual. + +.. _node-scram-sha-256: + +SCRAM-SHA-256 +------------- + +.. note:: + + ``SCRAM-SHA-256`` is the default authentication method for MongoDB starting + in version 4.0 + +``SCRAM-SHA-256`` is a SCRAM version that uses your username and password, +encrypted with the ``SHA-256`` algorithm to authenticate your user. + +You can specify this authentication mechanism by setting the ``authMechanism`` +to the value ``SCRAM-SHA-256`` in the +:manual:`connection string ` as shown in the +following sample code. + +.. important:: + Always **URI encode** the username and password using the + ``encodeURIComponent`` method to ensure they are correctly parsed. + +.. literalinclude:: /code-snippets/authentication/sha256.js + :language: javascript + +.. _node-scram-sha-1: + +SCRAM-SHA-1 +----------- + +.. note:: + ``SCRAM-SHA-1`` is the default authentication method for MongoDB versions + 3.0, 3.2, 3.4, and 3.6. + +``SCRAM-SHA-1`` is a SCRAM version that uses your +username and password, encrypted with the ``SHA-1`` algorithm to authenticate +your user. + +You can specify this authentication mechanism by setting the ``authMechanism`` +parameter to the value ``SCRAM-SHA-1`` in the +:manual:`connection string ` as shown +in the following sample code. + +.. important:: + Always **URI encode** the username and password using the + ``encodeURIComponent`` method to ensure they are correctly parsed. + +.. literalinclude:: /code-snippets/authentication/sha1.js + :language: javascript + +API Documentation +----------------- + +To learn more about any of the methods or types discussed on this +page, see the following API documentation: + +- `MongoClient <{+api+}/classes/MongoClient.html>`__ diff --git a/source/security/authentication/x509.txt b/source/security/authentication/x509.txt new file mode 100644 index 000000000..3595f9082 --- /dev/null +++ b/source/security/authentication/x509.txt @@ -0,0 +1,122 @@ +.. _node-authentication-x509: + +============================== +X.509 Authentication Mechanism +============================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: certificate, code example + +Overview +-------- + +In the **X.509** authentication mechanism, the server and client use the +:wikipedia:`TLS ` protocol to exchange X.509 public-key +certificates. You can use this mechanism to authenticate to MongoDB Atlas, MongoDB +Enterprise Advanced, and MongoDB Community Edition. + +.. tip:: X.509 Mechanism + + To learn how to use TLS/SSL with the {+driver-short+}, + see the :ref:`node-tls` guide. + + For more information about X.509 certificates, see + :manual:`Use x.509 Certificates to Authenticate Clients on Self-Managed Deployments + ` in the {+mdb-server+} manual. + +Code Placeholders +~~~~~~~~~~~~~~~~~ + +The code examples on this page use the following placeholders: + +- ````: The network address of your MongoDB deployment. +- ````: The path to your client PEM certificate file. + +To use the code examples, replace these placeholders with your own values. + +Specify X.509 Authentication +---------------------------- + +You can specify this authentication mechanism by setting the following +parameters of your :manual:`connection string `: + +- Set the ``authMechanism`` parameter to ``MONGODB-X509`` +- Set the ``tls`` parameter to ``true`` + +Pass the location of your client certificate file as the value of +``tlsCertificateKeyFile`` as a parameter of the connection URI. + +.. important:: + Always **URI encode** the certificate file path using the + ``encodeURIComponent`` method to ensure it is parsed correctly. + +.. literalinclude:: /code-snippets/authentication/x509.js + :language: javascript + +TLS Options +~~~~~~~~~~~ + +The following table describes the TLS options that you can set in a +connection URI. + +.. list-table:: + :widths: 35 12 10 43 + :header-rows: 1 + + * - Parameter Name + - Type + - Default Value + - Description + + * - ``tls`` + - boolean + - ``false`` + - Specifies whether to enable TLS on the connection. + + * - ``tlsInsecure`` + - boolean + - ``false`` + - Specifies whether to allow invalid certificates and mismatched + hostnames. When set to ``true``, this is equivalent to setting + ``tlsAllowInvalidCertificates`` and ``tlsAllowInvalidHostnames`` to + ``true``. + + * - ``tlsCAFile`` + - string + - + - Path to file that contains a single or bundle of trusted certificate + authorities used in a TLS connection. + + * - ``tlsCertificateKeyFile`` + - string + - + - Path to the client certificate file or the client private key file. If + both are required, the two must be concatenated into a single file. + + * - ``tlsCertificateKeyFilePassword`` + - buffer or string + - + - String or buffer that contains the password to decrypt the client + private key. + + * - ``tlsAllowInvalidCertificates`` + - boolean + - ``false`` + - Specifies whether the driver permits an invalid certificate to be used + to connect. + + * - ``tlsAllowInvalidHostnames`` + - boolean + - ``false`` + - Specifies whether the driver raises an error when there is a mismatch between the + server hostname and TLS certificate hostname. 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 97% rename from source/fundamentals/typescript.txt rename to source/typescript.txt index 872c23de9..16418170d 100644 --- a/source/fundamentals/typescript.txt +++ b/source/typescript.txt @@ -1,8 +1,9 @@ -.. node-fundamentals-typescript: +.. _node-fundamentals-typescript: +.. _node-typescript: -========== -TypeScript -========== +=================================== +TypeScript Features and Limitations +=================================== .. facet:: :name: genre @@ -93,8 +94,9 @@ The following classes accept all type parameters: - `AggregationCursor <{+api+}/classes/AggregationCursor.html>`__ You can find a code snippet that shows how to specify a type for the ``FindCursor`` -class in the -:ref:`Find Multiple Documents Usage Example `. +class in the :ref:`find() Example: Full File +` section of the :ref:`node-find` +guide. .. _node-ts-type-safety: @@ -204,7 +206,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 deleted file mode 100644 index 7b44da38d..000000000 --- a/source/usage-examples.txt +++ /dev/null @@ -1,129 +0,0 @@ -.. _node-usage-examples: - -============== -Usage Examples -============== - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :description: Learn how to load sample data into a MongoDB Atlas deployment and run Node.js driver usage examples. - :keywords: node.js - -.. contents:: On this page - :local: - :backlinks: none - :depth: 1 - :class: singlecol - -.. toctree:: - - Find - Insert - Update & Replace - Delete - Count Documents - Distinct Field Values - Run a Command - Watch for Changes - Bulk Operations - Perform a Transaction - -Overview --------- - -Usage examples provide convenient starting points for popular MongoDB -operations. Each example provides the following information: - -- Explanation of the operation in the example, including the - purpose and a sample use case for the method - -- Explanation of how to use the operation, including parameters, - return values, and common exceptions you might encounter - -- Full Node.js program that you can copy and paste to run the example - in your own environment - -How to Use the Usage Examples ------------------------------ - -These examples use the -:atlas:`MongoDB Atlas sample data ` -database. You can use this sample data on the free tier -of MongoDB Atlas by following the :atlas:`Get Started with Atlas -` guide or you -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 -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: - -.. code-block:: javascript - - // Replace the following with your MongoDB deployment's connection string. - const uri = - "mongodb+srv://:@?retryWrites=true&writeConcern=majority"; - -All examples use ES module imports. You can -`enable ES module imports `__ -by adding the following key-value pair to your package.json file: - -.. code-block:: json - - "type": "module" - -.. note:: CommonJS - - You can use any usage example with CommonJS ``require``. To use CommonJS ``require``, you - must swap out the ES module ``import`` statement for your CommonJS ``require`` - statement. - - Click on the tabs to see the syntax for importing the driver with ES module - ``import`` and CommonJS ``require``: - - .. tabs:: - - .. tab:: ES Module - :tabid: es-module - - .. code-block:: javascript - - import { MongoClient } from 'mongodb' - - .. tab:: CommonJS Module - :tabid: commonjs-module - - .. code-block:: javascript - - const { MongoClient } = require('mongodb') - -You can use the :guides:`Atlas Connectivity Guide -` to enable connectivity to your instance of -Atlas and find the :manual:`connection string -` to replace the ``uri`` variable in the -usage example. If your instance uses :manual:`SCRAM authentication -`, you can replace ```` with your username, -```` with your password, and ```` with the IP -address or URL of your instance. Consult the -:doc:`Connection Guide ` for more information -about getting connected to your MongoDB instance. - -Available Usage Examples ------------------------- - -- :doc:`Find Operations ` -- :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 ` diff --git a/source/usage-examples/bulkWrite.txt b/source/usage-examples/bulkWrite.txt deleted file mode 100644 index 07f6a9089..000000000 --- a/source/usage-examples/bulkWrite.txt +++ /dev/null @@ -1,101 +0,0 @@ -.. _node-usage-bulk: - -======================= -Perform Bulk Operations -======================= - -.. meta:: - :description: Perform batch write operations using the bulkWrite() method in the MongoDB Node.js Driver to increase throughput and performance by reducing network round trips. - -.. default-domain:: mongodb - -The ``bulkWrite()`` method performs batch write operations against a -*single* collection. This method reduces the number of network round trips from -your application to the server which therefore increases the throughput and -performance. Bulk writes return a collection of results for all operations -only after *all* operations passed to the method complete. - -You can specify one or more of the following write operations in -``bulkWrite()``: - -- ``insertOne`` -- ``updateOne`` -- ``updateMany`` -- ``deleteOne`` -- ``deleteMany`` -- ``replaceOne`` - -The ``bulkWrite()`` method accepts the following parameters: - -- ``operations``: specifies the bulk write operations to - perform. Pass each operation to ``bulkWrite()`` as an object in - an array. For examples that show the syntax for each write operation, see - the `bulkWrite API documentation <{+api+}/classes/Collection.html#bulkWrite>`__. - -- ``options``: *optional* settings that affect the execution - of the operation, such as whether the write operations executes in - sequential order and the write concern. - - By default, MongoDB executes bulk write operations one-by-one in the specified order - (serially). During an ordered bulk write, if an error occurs during the processing of an - operation, MongoDB returns without processing the remaining operations in the list. In - contrast, when ``ordered`` is ``false``, MongoDB continues to process remaining write - operations in the list. Unordered operations are theoretically faster since MongoDB can - execute them in parallel, but only use them if the writes do not depend on order. - -If you create an index with a :manual:`unique index ` -constraint, you might encounter a duplicate key write error during an -operation in the following format: - -.. code-block:: sh - - Error during bulkWrite, BulkWriteError: E11000 duplicate key error collection: ... - -Similarly, if you attempt to perform a bulk write against a collection -that uses :manual:`schema validation `, you may -encounter warnings or errors related to the formatting of inserted or -modified documents. - -Example -------- - -The following code sample performs a bulk write operation on the -``theaters`` collection in the ``sample_mflix`` database. The example call -to ``bulkWrite()`` includes examples of ``insertOne``, ``updateMany``, and -``deleteOne`` write operations: - -.. include:: /includes/connect-guide-note.rst - -.. tabs:: - - .. tab:: JavaScript - :tabid: javascript - - .. literalinclude:: /code-snippets/usage-examples/bulkWrite.js - :language: javascript - :linenos: - - .. tab:: TypeScript - :tabid: typescript - - .. literalinclude:: /code-snippets/usage-examples/bulkWrite.ts - :language: typescript - :linenos: - -Running the preceding example results in the following output: - -.. code-block:: javascript - :copyable: false - - BulkWriteResult { - insertedCount: 2, - matchedCount: 1, - modifiedCount: 1, - deletedCount: 0, - upsertedCount: 0, - upsertedIds: {}, - insertedIds: { - '0': new ObjectId("..."), - '1': new ObjectId("...") - } - } diff --git a/source/usage-examples/command.txt b/source/usage-examples/command.txt deleted file mode 100644 index 971fe227d..000000000 --- a/source/usage-examples/command.txt +++ /dev/null @@ -1,71 +0,0 @@ -.. _node-run-command-usageex: - -.. facet:: - :name: genre - :values: tutorial - -.. meta:: - :keywords: code example, multiple, modify, customize, debug - :description: Execute database commands using the command() method on a database instance with the MongoDB Node.js Driver. - -===================== -Run a Command Example -===================== - -You can execute database commands by using the -`command() <{+api+}/classes/Db.html#command>`__ method on a ``Db`` -instance. - -You can specify a command and options in a document. To run the -command, pass this document to the ``command()`` method. To see a full -list of database commands, see :manual:`Database Commands -` in the Server manual. - -.. tip:: - - Use the :mongosh:`MongoDB Shell ` for administrative tasks instead of - the {+driver-short+} whenever possible. - -You can specify optional command behavior by passing a -``RunCommandOptions`` object to the ``command()`` method. To learn more -about the supported options, see the -`Db.command() API documentation <{+api+}/classes/Db.html#command>`__. - -Example -------- - -.. include:: /includes/connect-guide-note.rst - -.. tabs:: - - .. tab:: JavaScript - :tabid: javascript - - .. literalinclude:: /code-snippets/usage-examples/command.js - :language: javascript - :linenos: - - .. tab:: TypeScript - :tabid: typescript - - .. literalinclude:: /code-snippets/usage-examples/command.js - :language: javascript - :linenos: - -.. note:: Identical Code Snippets - - The JavaScript and TypeScript code snippets above are identical. There are no - TypeScript specific features of the driver relevant to this use case. - -Running the preceding command, you see the following output: - -.. code-block:: javascript - :copyable: false - - { - db: 'sample_mflix', - collections: 6, - views: 0, - objects: 75620, - ... - } diff --git a/source/usage-examples/delete-operations.txt b/source/usage-examples/delete-operations.txt deleted file mode 100644 index 663fbbc68..000000000 --- a/source/usage-examples/delete-operations.txt +++ /dev/null @@ -1,18 +0,0 @@ -================= -Delete Operations -================= - -.. meta:: - :description: Explore examples of deleting single or multiple documents using the MongoDB Node.js Driver. - -.. default-domain:: mongodb - -.. toctree:: - :caption: Examples - - Delete a Document - Delete Multiple Documents - -- :doc:`Delete a Document ` - -- :doc:`Delete Multiple Documents ` diff --git a/source/usage-examples/deleteMany.txt b/source/usage-examples/deleteMany.txt deleted file mode 100644 index 761307040..000000000 --- a/source/usage-examples/deleteMany.txt +++ /dev/null @@ -1,65 +0,0 @@ -.. _node-usage-deletemany: - -========================= -Delete Multiple Documents -========================= - -.. meta:: - :description: Delete multiple document in a collection with the MongoDB Node.js Driver by using the deleteMany() method with a query to specify which documents to remove. - -.. default-domain:: mongodb - -You can delete multiple documents in a collection at once using the -`collection.deleteMany() <{+api+}/classes/Collection.html#deleteMany>`__ method. -Pass a query document to the ``deleteMany()`` method to specify a subset -of documents in the collection to delete. If you do not provide a query -document (or if you provide an empty document), MongoDB matches all documents -in the collection and deletes them. While you can use ``deleteMany()`` -to delete all documents in a collection, consider using -`drop() <{+api+}/classes/Collection.html#drop>`__ instead for better performance -and clearer code. - -You can specify more options in the ``options`` object passed in -the second parameter of the ``deleteMany()`` method. For more detailed -information, see the -`deleteMany() API documentation <{+api+}/classes/Collection.html#deleteMany>`__. - -Example -------- - -The following snippet deletes multiple documents from the ``movies`` -collection. It uses a **query document** that configures the query to -match and delete movies with the title "Santa Claus". - -.. include:: /includes/connect-guide-note.rst - -.. tabs:: - - .. tab:: JavaScript - :tabid: javascript - - .. literalinclude:: /code-snippets/usage-examples/deleteMany.js - :language: javascript - :linenos: - - .. tab:: TypeScript - :tabid: typescript - - .. literalinclude:: /code-snippets/usage-examples/deleteMany.ts - :language: typescript - :linenos: - -Running the preceding example for the first time, you see the following output: - -.. code-block:: none - :copyable: false - - Deleted 19 documents - -If you run the example more than once, you see the following output because -you deleted the matching documents in the first run: - -.. code-block:: none - :copyable: false - - Deleted 0 documents diff --git a/source/usage-examples/deleteOne.txt b/source/usage-examples/deleteOne.txt deleted file mode 100644 index 693766a1a..000000000 --- a/source/usage-examples/deleteOne.txt +++ /dev/null @@ -1,77 +0,0 @@ -.. _node-usage-deleteone: - -================= -Delete a Document -================= - -.. meta:: - :description: Delete a single document from a collection with the MongoDB Node.js Driver by using the deleteOne() method with a query to match the document. - -.. default-domain:: mongodb - -You can delete a single document in a collection with -``collection.deleteOne()``. -The ``deleteOne()`` method uses a query document that you provide -to match the subset of the documents in the collection that match -the query. If you do not provide a query document (or if you provide an -empty document), MongoDB matches all documents in the collection and -deletes the first match. - -You can specify more query options using the -``options`` object passed as the second parameter of the -``deleteOne`` method. For more information on this method, -see the -`deleteOne() API documentation <{+api+}/classes/Collection.html#deleteOne>`__. - -.. note:: - - If your application requires the deleted document after deletion, - consider using the - `collection.findOneAndDelete() <{+api+}/classes/Collection.html#findOneAndDelete>`__ - method, which has a similar interface to ``deleteOne()`` but also - returns the deleted document. - -Example -------- - -The following snippet deletes a single document from the ``movies`` -collection. It uses a **query document** that configures the query -to match movies with a ``title`` value of "Annie Hall". - -.. include:: /includes/connect-guide-note.rst - -.. tabs:: - - .. tab:: JavaScript - :tabid: javascript - - .. literalinclude:: /code-snippets/usage-examples/deleteOne.js - :language: javascript - :linenos: - - .. tab:: TypeScript - :tabid: typescript - - .. literalinclude:: /code-snippets/usage-examples/deleteOne.js - :language: javascript - :linenos: - -.. note:: Identical Code Snippets - - The JavaScript and TypeScript code snippets above are identical. There are no - TypeScript specific features of the driver relevant to this use case. - -Running the preceding example, you see the following output: - -.. code-block:: none - :copyable: false - - Successfully deleted one document. - -If you run the example more than once, you see the following output because -you deleted the matching document in the first run: - -.. code-block:: none - :copyable: false - - No documents matched the query. Deleted 0 documents. diff --git a/source/usage-examples/distinct.txt b/source/usage-examples/distinct.txt deleted file mode 100644 index 428760081..000000000 --- a/source/usage-examples/distinct.txt +++ /dev/null @@ -1,80 +0,0 @@ -.. _node-usage-distinct: - -=================================== -Retrieve Distinct Values of a Field -=================================== - -.. meta:: - :description: Retrieve distinct values of a field in a collection using the distinct() method in the MongoDB Node.js Driver, with examples in JavaScript and TypeScript. - -.. default-domain:: mongodb - -You can retrieve a list of distinct values for a field across a collection by using -the `collection.distinct() <{+api+}/classes/Collection.html#distinct>`__ -method. Call the ``distinct()`` method on a ``Collection`` object with a document -field name parameter as a ``String`` to produce a list that contains one of each -of the different values found in the specified document field as shown below: - -.. code-block:: javascript - - const distinctValues = myColl.distinct("countries", query); - -You can specify a document field within an *embedded document* using -:manual:`dot notation `. If you call -``distinct()`` on an document field that contains an array, the method -treats each element as a separate value. See the following example of -a method call to the ``wins`` field in the ``awards`` subdocument: - -.. code-block:: javascript - - const distinctValues = myColl.distinct("awards.wins", query); - -You can specify more query options using the ``options`` object passed -as the third parameter to the ``distinct()`` method. For details on the -query parameters, see the -`distinct() method in the API documentation <{+api+}/classes/Collection.html#distinct>`__. - -If you specify a value for the document field name that is not of type -``String`` such as a ``Document``, ``Array``, ``Number``, or ``null``, -the method does not execute and returns a ``TypeMismatch`` error with a -message that resembles the following: - -.. blockquote:: - - "key" had the wrong type. Expected string, found - -Visit :ref:`node-fundamentals-distinct` for more information about the ``distinct()`` -method. - -Example -------- - -The following snippet retrieves a list of distinct values for the ``year`` -document field from the ``movies`` collection. It uses a query document to -match movies that include "Barbara Streisand" as a ``director``. - -.. include:: /includes/connect-guide-note.rst - -.. tabs:: - - .. tab:: JavaScript - :tabid: javascript - - .. literalinclude:: /code-snippets/usage-examples/distinct.js - :language: javascript - :linenos: - - .. tab:: TypeScript - :tabid: typescript - - .. literalinclude:: /code-snippets/usage-examples/distinct.ts - :language: typescript - :linenos: - -Running the preceding example, you see the following output: - -.. code-block:: json - :copyable: false - - [ 1983, 1991, 1996 ] - diff --git a/source/usage-examples/find-operations.txt b/source/usage-examples/find-operations.txt deleted file mode 100644 index ca37cc69c..000000000 --- a/source/usage-examples/find-operations.txt +++ /dev/null @@ -1,16 +0,0 @@ -=============== -Find Operations -=============== - -.. meta:: - :description: Learn by example: how to create queries and retrieve data from MongoDB by using the {+driver-long+}. - -.. toctree:: - :caption: Examples - - Find a Document - Find Multiple Documents - -- :doc:`Find a Document ` - -- :doc:`Find Multiple Documents ` diff --git a/source/usage-examples/find.txt b/source/usage-examples/find.txt deleted file mode 100644 index e88bbb51c..000000000 --- a/source/usage-examples/find.txt +++ /dev/null @@ -1,108 +0,0 @@ -.. _node-usage-find: - -======================= -Find Multiple Documents -======================= - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :description: Learn how to retrieve multiple documents from MongoDB by using the Node.js driver. - :keywords: code example, node.js, sample dataset - -You can query for multiple documents in a collection with -``collection.find()``. The ``find()`` method uses a query document that you -provide to match the subset of the documents in the collection that match the -query. If you don't provide a query document (or if you provide an empty -document), MongoDB returns all documents in the collection. For more -information on querying MongoDB, see our -:doc:`documentation on query documents `. - -You can also define more query options such as -:doc:`sort ` -and -:doc:`projection ` -to configure the result set. You can specify these in the options -parameter in your ``find()`` method call in ``sort`` and ``projection`` -objects. See `collection.find() <{+api+}/classes/Collection.html#find>`__ for more -information on the parameters you can pass to the method. - -The ``find()`` method returns a `FindCursor <{+api+}/classes/FindCursor.html>`__ that -manages the results of your query. You can iterate through the matching -documents using the ``for await...of`` syntax, or one of the following -:ref:`cursor methods `: - -- ``next()`` -- ``toArray()`` - -If no documents match the query, ``find()`` returns an empty cursor. - -Compatibility -------------- - -.. |page-topic| replace:: use the ``find()`` method -.. |link-topic-ing| replace:: finding documents 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 - -Example -------- - -The following snippet finds documents from the ``movies`` collection. It -uses the following parameters: - -- A **query document** that configures the query to return only - movies with a runtime of less than 15 minutes. - -- A **sort** that organizes returned documents in ascending order by - title (alphabetical order in which "A" comes before "Z" and "1" before - "9"). - -- A **projection** that explicitly excludes the ``_id`` field from - returned documents and explicitly includes only the ``title`` and - ``imdb`` object (and its embedded fields). - -.. include:: /includes/connect-guide-note.rst - -.. _node-driver-find-usage-example-code-snippet: - -.. tabs:: - - .. tab:: JavaScript - :tabid: javascript - - .. literalinclude:: /code-snippets/usage-examples/find.js - :language: javascript - :linenos: - - .. tab:: TypeScript - :tabid: typescript - - .. literalinclude:: /code-snippets/usage-examples/find.ts - :language: typescript - :linenos: - -Running the preceding example, you see the following output: - -.. code-block:: javascript - :copyable: false - - { title: '10 Minutes', imdb: { rating: 7.9, votes: 743, id: 339976 } } - { title: '3x3', imdb: { rating: 6.9, votes: 206, id: 1654725 } } - { title: '7:35 in the Morning', imdb: { rating: 7.3, votes: 1555, id: 406501 } } - { title: '8', imdb: { rating: 7.8, votes: 883, id: 1592502 } } - ... - -The ``sort`` and ``projection`` options can also be specified as methods -(``sort()`` and ``project()``) chained to the ``find()`` method. -The following two commands are equivalent: - -.. code-block:: javascript - - movies.find({ runtime: { $lt: 15 } }, { sort: { title: 1 }, projection: { _id: 0, title: 1, imdb: 1 }}); - movies.find({ runtime: { $lt: 15 } }).sort({ title: 1}).project({ _id: 0, title: 1, imdb: 1 }); diff --git a/source/usage-examples/findOne.txt b/source/usage-examples/findOne.txt deleted file mode 100644 index 94e674155..000000000 --- a/source/usage-examples/findOne.txt +++ /dev/null @@ -1,87 +0,0 @@ -.. _node-usage-findone: - -=============== -Find a Document -=============== - -.. default-domain:: mongodb - -.. facet:: - :name: genre - :values: tutorial - -.. meta:: - :description: Learn how to retrieve one document from MongoDB by using the Node.js driver. - :keywords: code example, node.js, sample dataset - -You can query for a single document in a collection with the -``collection.findOne()`` method. The ``findOne()`` method uses a query -document that you provide to match only the subset of the documents in the -collection that match the query. If you don't provide a query document or if -you provide an empty document, MongoDB matches all documents in the -collection. The ``findOne()`` operation only returns the first matched -document. For more information on querying MongoDB, see our -:doc:`documentation on query documents `. - -You can also define more query options such as -:doc:`sort ` -and :doc:`projection ` -to configure the returned document. You can specify the more options -in the ``options`` object passed as the second parameter of the -``findOne`` method. For detailed reference documentation, see -`collection.findOne() <{+api+}/classes/Collection.html#findOne>`__. - -Compatibility -------------- - -.. |page-topic| replace:: use the ``findOne()`` method -.. |link-topic-ing| replace:: finding documents 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 - -Example -------- - -The following snippet finds a single document from the ``movies`` -collection. It uses the following parameters: - -- A **query document** that configures the query to return only - movies with the title of exactly the text ``'The Room'``. - -- A **sort** that organizes matched documents in descending order by - rating, so if our query matches multiple documents the returned - document will be the document with the highest rating. - -- A **projection** that explicitly excludes the ``_id`` field from - returned documents and explicitly includes only the ``title`` and - ``imdb`` object (and its embedded fields). - -.. include:: /includes/connect-guide-note.rst - -.. _node-driver-findone-usage-example-code-snippet: - -.. tabs:: - - .. tab:: JavaScript - :tabid: javascript - - .. literalinclude:: /code-snippets/usage-examples/findOne.js - :language: javascript - - .. tab:: TypeScript - :tabid: typescript - - .. literalinclude:: /code-snippets/usage-examples/findOne.ts - :language: typescript - - -Running the preceding example, you see the following output: - -.. code-block:: javascript - :copyable: false - - { title: 'The Room', imdb: { rating: 3.5, votes: 25673, id: 368226 } } - diff --git a/source/usage-examples/insert-operations.txt b/source/usage-examples/insert-operations.txt deleted file mode 100644 index e32ff60eb..000000000 --- a/source/usage-examples/insert-operations.txt +++ /dev/null @@ -1,16 +0,0 @@ -================= -Insert Operations -================= - -.. meta:: - :description: Learn by example: how to insert data into MongoDB by using the {+driver-long+}. - -.. toctree:: - :caption: Examples - - Insert a Document - Insert Multiple Documents - -- :doc:`Insert a Document ` - -- :doc:`Insert Multiple Documents ` diff --git a/source/usage-examples/insertMany.txt b/source/usage-examples/insertMany.txt deleted file mode 100644 index 3b89cfa79..000000000 --- a/source/usage-examples/insertMany.txt +++ /dev/null @@ -1,51 +0,0 @@ -.. _node-usage-insertmany: - -========================= -Insert Multiple Documents -========================= - -.. meta:: - :description: Insert multiple documents into a collection using the insertMany() method in the MongoDB Node.js Driver. - -.. default-domain:: mongodb - -You can insert multiple documents using the -`collection.insertMany() <{+api+}/classes/Collection.html#insertMany>`__ method. The ``insertMany()`` takes an array -of documents to insert into the specified collection. - -You can specify more options in the ``options`` object passed as the -second parameter of the ``insertMany()`` method. Specify ``ordered:true`` -to prevent inserting the remaining documents if the insertion failed for a -previous document in the array. - -Specifying incorrect parameters for your ``insertMany()`` operation can -cause problems. Attempting to insert a field with a value that violates -unique index rules results in a ``duplicate key error``. - -Example -------- - -.. include:: /includes/connect-guide-note.rst - -.. tabs:: - - .. tab:: JavaScript - :tabid: javascript - - .. literalinclude:: /code-snippets/usage-examples/insertMany.js - :language: javascript - :linenos: - - .. tab:: TypeScript - :tabid: typescript - - .. literalinclude:: /code-snippets/usage-examples/insertMany.ts - :language: typescript - :linenos: - -Running the preceding example, you see the following output: - -.. code-block:: none - :copyable: false - - 3 documents were inserted diff --git a/source/usage-examples/insertOne.txt b/source/usage-examples/insertOne.txt deleted file mode 100644 index 1e473972d..000000000 --- a/source/usage-examples/insertOne.txt +++ /dev/null @@ -1,70 +0,0 @@ -.. _node-usage-insert: - -================= -Insert a Document -================= - -.. default-domain:: mongodb - -.. facet:: - :name: genre - :values: tutorial - -.. meta:: - :description: Learn how to insert a document into MongoDB by using the Node.js driver. - :keywords: code example, node.js, sample dataset - -You can insert a document into a collection using the -`collection.insertOne() <{+api+}/classes/Collection.html#insertOne>`__ method. To -insert a document, define an object that contains the fields and values that -you want to store. If the specified collection does not exist, the -``insertOne()`` method creates the collection. - -You can specify more query options using the ``options`` parameter. -For more information on the method parameters, see the -`insertOne() API documentation <{+api+}/classes/Collection.html#insertOne>`__. -For more information on this method, see the -`insertOne() API documentation <{+api+}/classes/Collection.html#insertOne>`__. - -If the operation successfully inserts a document, it appends an -``insertedId`` field to the object passed in the method call, and sets the -value of the field to the ``_id`` of the inserted document. - -Compatibility -------------- - -.. |page-topic| replace:: use the ``insertOne()`` method -.. |link-topic-ing| replace:: inserting documents 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 - -Example -------- - -.. include:: /includes/connect-guide-note.rst - -.. tabs:: - - .. tab:: JavaScript - :tabid: javascript - - .. literalinclude:: /code-snippets/usage-examples/insertOne.js - :language: javascript - :linenos: - - .. tab:: TypeScript - :tabid: typescript - - .. literalinclude:: /code-snippets/usage-examples/insertOne.ts - :language: typescript - :linenos: - -Running the preceding example, you see the following output: - -.. code-block:: none - :copyable: false - - A document was inserted with the _id: diff --git a/source/usage-examples/replaceOne.txt b/source/usage-examples/replaceOne.txt deleted file mode 100644 index fc6d5ee3b..000000000 --- a/source/usage-examples/replaceOne.txt +++ /dev/null @@ -1,64 +0,0 @@ -.. _node-usage-replaceone: - -================== -Replace a Document -================== - -.. meta:: - :description: Replace a single document in a collection using the replaceOne() method in the MongoDB Node.js Driver, with options for upsert and error handling. - -.. default-domain:: mongodb - -You can replace a single document using the -`collection.replaceOne() <{+api+}/classes/Collection.html#replaceOne>`__ method. -``replaceOne()`` accepts a query document and a replacement document. If -the query matches a document in the collection, it replaces the first -document that matches the query with the provided replacement document. -This operation removes all fields and values in the original document and -replaces them with the fields and values in the replacement document. The -value of the ``_id`` field remains the same unless you explicitly specify -a new value for ``_id`` in the replacement document. - -You can specify more options, such as ``upsert``, using the -optional ``options`` parameter. If you set the ``upsert`` option field to -``true`` the method inserts a new document if no document matches the query. - -The ``replaceOne()`` method throws an exception if an error occurs -during execution. For example, if you specify a value that violates a -unique index rule, ``replaceOne()`` throws a ``duplicate key error``. - -.. note:: - - If your application requires the document after updating, - use the `collection.findOneAndReplace() <{+api+}/classes/Collection.html#findOneAndReplace>`__ - method which has a similar interface to ``replaceOne()``. - You can configure ``findOneAndReplace()`` to return either the - original matched document or the replacement document. - -Example -------- - -.. include:: /includes/connect-guide-note.rst - -.. tabs:: - - .. tab:: JavaScript - :tabid: javascript - - .. literalinclude:: /code-snippets/usage-examples/replaceOne.js - :language: javascript - :linenos: - - .. tab:: TypeScript - :tabid: typescript - - .. literalinclude:: /code-snippets/usage-examples/replaceOne.ts - :language: typescript - :linenos: - -Running the preceding example, you see the following output: - -.. code-block:: none - :copyable: false - - Modified 1 document(s) diff --git a/source/usage-examples/transactions.txt b/source/usage-examples/transactions.txt deleted file mode 100644 index 79277686f..000000000 --- a/source/usage-examples/transactions.txt +++ /dev/null @@ -1,20 +0,0 @@ -.. _node-usage-txns: - -===================== -Perform a Transaction -===================== - -.. meta:: - :description: Explore how to perform transactions using the MongoDB Node.js Driver with both the Convenient Transaction API and the Core API. - -.. toctree:: - :caption: Transaction Usage Examples - - Convenient Transaction API - Core API - -The following usage examples demonstrate how to perform transactions by -using the transaction APIs in the {+driver-short+}: - -- :ref:`node-usage-convenient-txn` -- :ref:`node-usage-core-txn` \ No newline at end of file diff --git a/source/usage-examples/update-and-replace-operations.txt b/source/usage-examples/update-and-replace-operations.txt deleted file mode 100644 index f60402c98..000000000 --- a/source/usage-examples/update-and-replace-operations.txt +++ /dev/null @@ -1,19 +0,0 @@ -=========================== -Update & Replace Operations -=========================== - -.. meta:: - :description: Learn by example: how to update and replace data in MongoDB by using the {+driver-long+}. - -.. toctree:: - :caption: Examples - - Update a Document - Update Multiple Documents - Replace a Document - -- :doc:`Update a Document ` - -- :doc:`Update Multiple Documents ` - -- :doc:`Replace a Document ` diff --git a/source/usage-examples/updateMany.txt b/source/usage-examples/updateMany.txt deleted file mode 100644 index da6329293..000000000 --- a/source/usage-examples/updateMany.txt +++ /dev/null @@ -1,51 +0,0 @@ -.. _node-usage-updatemany: - -========================= -Update Multiple Documents -========================= - -.. meta:: - :description: Update multiple documents in a collection with the MongoDB Node.js Driver by using the updateMany() method with a filter. - -.. default-domain:: mongodb - -You can update multiple documents using the -`collection.updateMany() <{+api+}/classes/Collection.html#updateMany>`__ method. -The ``updateMany()`` method accepts a filter document and an update document. If the query matches documents in the -collection, the method applies the updates from the update document to fields -and values of the matching documents. The update document requires an :manual:`update operator -` to modify a field in a document. - -You can specify more options in the ``options`` object passed in -the third parameter of the ``updateMany()`` method. For more detailed -information, see -`the updateMany() API documentation <{+api+}/classes/Collection.html#updateMany>`__. - - -Example -------- - -.. include:: /includes/connect-guide-note.rst - -.. tabs:: - - .. tab:: JavaScript - :tabid: javascript - - .. literalinclude:: /code-snippets/usage-examples/updateMany.js - :language: javascript - :linenos: - - .. tab:: TypeScript - :tabid: typescript - - .. literalinclude:: /code-snippets/usage-examples/updateMany.ts - :language: typescript - :linenos: - -Running the preceding example, you see the following output: - -.. code-block:: none - :copyable: false - - Updated 477 documents diff --git a/source/usage-examples/updateOne.txt b/source/usage-examples/updateOne.txt deleted file mode 100644 index 2034b693c..000000000 --- a/source/usage-examples/updateOne.txt +++ /dev/null @@ -1,73 +0,0 @@ -.. _node-usage-updateone: - -================= -Update a Document -================= - -.. meta:: - :description: Update a single document in a MongoDB collection with the in the MongoDB Node.js Driver by using the updateOne() method with options for upserting and handling exceptions. - -.. default-domain:: mongodb - -You can update a single document using the -`collection.updateOne() <{+api+}/classes/Collection.html#updateOne>`__ -method. The ``updateOne()`` method accepts a filter -document and an update document. If the query matches documents in the -collection, the method applies the updates from the update document to fields -and values of them. The update document contains :manual:`update operators -` that instruct the method -on the changes to make to the matches. - -You can specify more query options using the ``options`` object -passed as the second parameter of the ``updateOne()`` method. -Set the ``upsert`` option to ``true`` to create a new document -if no documents match the filter. For more information, see the -`updateOne() API documentation <{+api+}/classes/Collection.html#updateOne>`__. - -``updateOne()`` throws an exception if an error occurs during execution. -If you specify a value in your update document for the immutable field -``_id``, the method throws an exception. If your update document contains -a value that violates unique index rules, the method throws a ``duplicate -key error`` exception. - -.. note:: - - If your application requires the document after updating, - consider using the - `collection.findOneAndUpdate() <{+api+}/classes/Collection.html#findOneAndUpdate>`__. - method, which has a similar - interface to ``updateOne()`` but also returns the original or updated - document. - -Example -------- - -The following example uses the ``$set`` update operator which specifies -update values for document fields. For more information on update operators, -see the :manual:`MongoDB update operator reference documentation -`. - -.. include:: /includes/connect-guide-note.rst - -.. tabs:: - - .. tab:: JavaScript - :tabid: javascript - - .. literalinclude:: /code-snippets/usage-examples/updateOne.js - :language: javascript - :linenos: - - .. tab:: TypeScript - :tabid: typescript - - .. literalinclude:: /code-snippets/usage-examples/updateOne.ts - :language: typescript - :linenos: - -If you run the example above, you see the following output: - -.. code-block:: none - :copyable: false - - 1 document(s) matched the filter, updated 1 document(s)