diff --git a/config/redirects b/config/redirects index acac87bf9..ef2106bc8 100644 --- a/config/redirects +++ b/config/redirects @@ -26,6 +26,8 @@ raw: ${prefix}/stable -> ${base}/current/ [*-v6.0)]: ${prefix}/${version}/fundamentals/connection/socks/ -> ${base}/${version}/ +# Comprehensive Coverage Redirects + [*-master]: ${prefix}/${version}/quick-start/download-and-install/ -> ${base}/${version}/get-started/ [*-master]: ${prefix}/${version}/quick-start/create-a-deployment/ -> ${base}/${version}/get-started/ [*-master]: ${prefix}/${version}/quick-start/create-a-connection-string/ -> ${base}/${version}/get-started/ @@ -49,7 +51,6 @@ raw: ${prefix}/stable -> ${base}/current/ [*-master]: ${prefix}/${version}/fundamentals/gridfs/ -> ${base}/${version}/crud/gridfs/ [*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/retrieve/ -> ${base}/${version}/crud/query/retrieve/ [*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/project/ -> ${base}/${version}/crud/query/project/ -[*-master]: ${prefix}/${version}/fundamentals/usage-examples/count/ -> ${base}/${version}/crud/query/count/ [*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/distinct/ -> ${base}/${version}/crud/query/distinct/ [*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/cursor/ -> ${base}/${version}/crud/query/cursor/ [*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/geo/ -> ${base}/${version}/crud/query/geo/ @@ -83,6 +84,23 @@ raw: ${prefix}/stable -> ${base}/current/ [*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/modify/ -> ${base}/crud/update/modify/ [*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/embedded-arrays/ -> ${base}/crud/update/embedded-arrays/ [*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/pkFactory/ -> ${base}/crud/pkFactory/ - -# Comprehensive Coverage Redirects [*-master]: ${prefix}/${version}/security/authentication/enterprise-mechanisms/ -> ${base}/security/authentication + +# Usage Example Redirects + +[*-master]: ${prefix}/${version}/usage-examples/findOne/ -> ${base}/crud/query/retrieve/ +[*-master]: ${prefix}/${version}/usage-examples/find/ -> ${base}/crud/query/retrieve/ +[*-master]: ${prefix}/${version}/usage-examples/insertOne/ -> ${base}/crud/insert/ +[*-master]: ${prefix}/${version}/usage-examples/insertMany/ -> ${base}/crud/insert/ +[*-master]: ${prefix}/${version}/usage-examples/updateOne/ -> ${base}/crud/update/modify/ +[*-master]: ${prefix}/${version}/usage-examples/updateMany/ -> ${base}/crud/update/modify/ +[*-master]: ${prefix}/${version}/usage-examples/replaceOne/ -> ${base}/crud/update/replace/ +[*-master]: ${prefix}/${version}/usage-examples/deleteOne/ -> ${base}/crud/delete/ +[*-master]: ${prefix}/${version}/usage-examples/deleteMany/ -> ${base}/crud/delete/ +[*-master]: ${prefix}/${version}/usage-examples/count/ -> ${base}/crud/query/count/ +[*-master]: ${prefix}/${version}/usage-examples/distinct/ -> ${base}/crud/query/distinct/ +[*-master]: ${prefix}/${version}/usage-examples/command/ -> ${base}/run-command/ +[*-master]: ${prefix}/${version}/usage-examples/bulkWrite/ -> ${base}/bulk-write/ +[*-master]: ${prefix}/${version}/usage-examples/transactions/ -> ${base}/crud/transactions/ +[*-master]: ${prefix}/${version}/usage-examples/transaction-conv/ -> ${base}/crud/transactions/transaction-conv/ +[*-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 b1304ec09..880ba4760 100644 --- a/snooty.toml +++ b/snooty.toml @@ -15,11 +15,12 @@ toc_landing_pages = [ "/security/authentication", "/aggregation-tutorials", "/data-formats", - "connect/connection-options", - "crud", + "/connect/connection-options", + "/crud", "/crud/query", "crud/update", - "monitoring-and-logging" + "/crud/transactions", + "/monitoring-and-logging" ] sharedinclude_root = "https://raw.githubusercontent.com/10gen/docs-shared/main/" diff --git a/source/archive-reference-files/collations.txt b/source/archive-reference-files/collations.txt index 2aff339ec..d54cc2af3 100644 --- a/source/archive-reference-files/collations.txt +++ b/source/archive-reference-files/collations.txt @@ -1,5 +1,4 @@ .. _node-fundamentals-collations: -.. _node-collations: ========== Collations 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/crud/bulk-write.txt b/source/crud/bulk-write.txt index 35c9c6310..100204b56 100644 --- a/source/crud/bulk-write.txt +++ b/source/crud/bulk-write.txt @@ -10,6 +10,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 +228,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 +307,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 +395,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 +482,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 +566,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 +643,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 +831,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/crud/delete.txt b/source/crud/delete.txt index c476a0eab..cb44023b9 100644 --- a/source/crud/delete.txt +++ b/source/crud/delete.txt @@ -8,9 +8,16 @@ Delete 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, delete data + Overview -------- @@ -25,6 +32,14 @@ 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: @@ -59,6 +74,86 @@ method calls above as follows: 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() `. +.. _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/crud/insert.txt b/source/crud/insert.txt index 51119f154..c2ad4a800 100644 --- a/source/crud/insert.txt +++ b/source/crud/insert.txt @@ -15,7 +15,7 @@ Insert Documents .. contents:: On this page :local: :backlinks: none - :depth: 1 + :depth: 2 :class: singlecol Overview @@ -45,8 +45,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 +114,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 +271,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/crud/query.txt b/source/crud/query.txt index b8e793575..b0d5f9cf7 100644 --- a/source/crud/query.txt +++ b/source/crud/query.txt @@ -157,7 +157,7 @@ Additional Information ~~~~~~~~~~~~~~~~~~~~~~ For runnable code examples that demonstrate find operations, see the following -usage examples: +examples: - :ref:`node-usage-findone` - :ref:`node-usage-find` diff --git a/source/crud/query/count.txt b/source/crud/query/count.txt index 9885211c3..1299bb121 100644 --- a/source/crud/query/count.txt +++ b/source/crud/query/count.txt @@ -5,8 +5,26 @@ Count Documents =============== -The Node.js driver provides two methods for counting documents in a -collection: +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. 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 @@ -24,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,41 +61,37 @@ documentation for each method for more information. collection.countDocuments({}, { hint: "_id_" }); -Example -------- +countDocuments() Example: Full File +----------------------------------- + +.. 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: - .. 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/crud/query/cursor.txt b/source/crud/query/cursor.txt index 6fecddd5f..74b9775d7 100644 --- a/source/crud/query/cursor.txt +++ b/source/crud/query/cursor.txt @@ -37,8 +37,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/crud/query/distinct.txt b/source/crud/query/distinct.txt index 96aa5ca06..99300a878 100644 --- a/source/crud/query/distinct.txt +++ b/source/crud/query/distinct.txt @@ -120,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:: @@ -162,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/crud/query/query-document.txt b/source/crud/query/query-document.txt index f24f3263f..e01bee4a7 100644 --- a/source/crud/query/query-document.txt +++ b/source/crud/query/query-document.txt @@ -10,7 +10,7 @@ Specify a Query .. contents:: On this page :local: :backlinks: none - :depth: 1 + :depth: 2 :class: singlecol Overview diff --git a/source/crud/query/retrieve.txt b/source/crud/query/retrieve.txt index 585d920b6..8b42501b4 100644 --- a/source/crud/query/retrieve.txt +++ b/source/crud/query/retrieve.txt @@ -16,7 +16,7 @@ Find Documents .. contents:: On this page :local: :backlinks: none - :depth: 1 + :depth: 2 :class: singlecol .. _nodejs-driver-retrieve-data-overview: @@ -42,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 @@ -144,14 +142,112 @@ 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 + + { title: 'The Room', imdb: { rating: 3.5, votes: 25673, id: 368226 } } + +.. _node-usage-find: -For runnable code examples that demonstrate find operations, see the following -usage examples: +find() Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~ -- :ref:`node-usage-findone` -- :ref:`node-usage-find` +.. 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 } } + ... + +You can also specify ``sort`` and ``projection`` options by chaining the +``sort()`` and ``projection`` methods 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 }); + +Additional Information +~~~~~~~~~~~~~~~~~~~~~~ For more information about the ``findOne()`` and ``find()`` methods, see the following Server manual documentation: @@ -234,8 +330,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/transactions.txt b/source/crud/transactions.txt index 4349208aa..9ce443bff 100644 --- a/source/crud/transactions.txt +++ b/source/crud/transactions.txt @@ -18,6 +18,12 @@ Transactions :depth: 2 :class: singlecol +.. toctree:: + :caption: Transaction Usage Examples + + Convenient Transaction API + Core API + Overview -------- 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 1d42d6591..5b44f6716 100644 --- a/source/usage-examples/transaction-conv.txt +++ b/source/crud/transactions/transaction-conv.txt @@ -4,6 +4,13 @@ Use the Convenient Transaction API ================================== +.. facet:: + :name: genre + :values: reference + +.. meta:: + :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 bc86f1343..2ef42de52 100644 --- a/source/usage-examples/transaction-core.txt +++ b/source/crud/transactions/transaction-core.txt @@ -4,6 +4,13 @@ Use the Core API ================ +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: modify, customize + .. contents:: On this page :local: :backlinks: none diff --git a/source/crud/update.txt b/source/crud/update.txt index 3784dc6e4..d35adc51d 100644 --- a/source/crud/update.txt +++ b/source/crud/update.txt @@ -15,7 +15,7 @@ Update Documents .. contents:: On this page :local: :backlinks: none - :depth: 1 + :depth: 2 :class: singlecol .. toctree:: @@ -35,9 +35,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 diff --git a/source/crud/update/modify.txt b/source/crud/update/modify.txt index 72e2917c6..0ef66fcdd 100644 --- a/source/crud/update/modify.txt +++ b/source/crud/update/modify.txt @@ -8,9 +8,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 -------- @@ -27,6 +34,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 @@ -140,89 +149,91 @@ 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 index 741b2a854..2099e331d 100644 --- a/source/crud/update/replace.txt +++ b/source/crud/update/replace.txt @@ -4,6 +4,12 @@ Replace Documents ================= +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + .. facet:: :name: genre :values: reference @@ -18,4 +24,146 @@ In this guide, you can learn how to use {+driver-short+} to perform a replace operation on a document in a MongoDB collection. A replace operation performs differently than an update operation. An update operation modifies only the specified fields in a target document. A replace operation removes *all* fields -in the target document and replaces them with new ones. \ No newline at end of file +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/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/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/monitoring-and-logging/change-streams.txt b/source/monitoring-and-logging/change-streams.txt index 4f5f0ed9c..3a63d6c85 100644 --- a/source/monitoring-and-logging/change-streams.txt +++ b/source/monitoring-and-logging/change-streams.txt @@ -1,4 +1,3 @@ -.. _node-usage-watch: .. _node-change-streams: ==================== @@ -114,37 +113,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:: - - .. tab:: JavaScript - :tabid: javascript - - .. literalinclude:: /code-snippets/usage-examples/changeStream.js - :language: javascript - :linenos: - - .. tab:: TypeScript - :tabid: typescript +.. include:: /includes/crud/example-identical-code.rst - .. 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 @@ -216,26 +202,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/reference/release-notes.txt b/source/reference/release-notes.txt index 9d497e2af..5cb53a579 100644 --- a/source/reference/release-notes.txt +++ b/source/reference/release-notes.txt @@ -709,7 +709,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/run-command.txt b/source/run-command.txt index d8f27b2e3..e73d2107e 100644 --- a/source/run-command.txt +++ b/source/run-command.txt @@ -1,8 +1,8 @@ .. _node-run-command: -============== -Run a Command -============== +====================== +Run a Database Command +====================== .. contents:: On this page :local: @@ -10,6 +10,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 -------- @@ -201,6 +209,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/typescript.txt b/source/typescript.txt index 4628cfaa6..417a17e22 100644 --- a/source/typescript.txt +++ b/source/typescript.txt @@ -93,8 +93,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: diff --git a/source/usage-examples.txt b/source/usage-examples.txt deleted file mode 100644 index f3c6d6e6b..000000000 --- a/source/usage-examples.txt +++ /dev/null @@ -1,130 +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:`get started guide ` to learn more about getting -started with Node.js, npm, and the Node.js driver. Once you've copied -a usage example, you must edit one line to get the example running -with your instance of MongoDB: - -.. 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:`Retrieve Distinct Values of a Field ` -- :doc:`Run a Command ` -- :doc:`Perform Bulk Operations ` -- :doc:`Perform a Transaction ` - -.. - :doc:`Count Documents ` -.. - :doc:`Watch for Changes ` diff --git a/source/usage-examples/bulkWrite.txt b/source/usage-examples/bulkWrite.txt deleted file mode 100644 index ee09f89a0..000000000 --- a/source/usage-examples/bulkWrite.txt +++ /dev/null @@ -1,98 +0,0 @@ -.. _node-usage-bulk: - -======================= -Perform Bulk Operations -======================= - -.. 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 855e98c87..000000000 --- a/source/usage-examples/command.txt +++ /dev/null @@ -1,70 +0,0 @@ -.. _node-run-command-usageex: - -.. facet:: - :name: genre - :values: tutorial - -.. meta:: - :keywords: code example, multiple, modify, customize, debug - -===================== -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 bc0a4ecb0..000000000 --- a/source/usage-examples/delete-operations.txt +++ /dev/null @@ -1,15 +0,0 @@ -================= -Delete Operations -================= - -.. 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 8019cced3..000000000 --- a/source/usage-examples/deleteMany.txt +++ /dev/null @@ -1,62 +0,0 @@ -.. _node-usage-deletemany: - -========================= -Delete Multiple Documents -========================= - -.. 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 e06cffad6..000000000 --- a/source/usage-examples/deleteOne.txt +++ /dev/null @@ -1,74 +0,0 @@ -.. _node-usage-deleteone: - -================= -Delete a 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 03ab182bd..000000000 --- a/source/usage-examples/distinct.txt +++ /dev/null @@ -1,77 +0,0 @@ -.. _node-usage-distinct: - -=================================== -Retrieve Distinct Values of a Field -=================================== - -.. 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 5bf4fb43b..000000000 --- a/source/usage-examples/insertMany.txt +++ /dev/null @@ -1,48 +0,0 @@ -.. _node-usage-insertmany: - -========================= -Insert Multiple Documents -========================= - -.. 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 a0fb6d4b4..000000000 --- a/source/usage-examples/replaceOne.txt +++ /dev/null @@ -1,61 +0,0 @@ -.. _node-usage-replaceone: - -================== -Replace a Document -================== - -.. 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 1d57c11f2..000000000 --- a/source/usage-examples/transactions.txt +++ /dev/null @@ -1,17 +0,0 @@ -.. _node-usage-txns: - -===================== -Perform a Transaction -===================== - -.. 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 035933362..000000000 --- a/source/usage-examples/updateMany.txt +++ /dev/null @@ -1,48 +0,0 @@ -.. _node-usage-updatemany: - -========================= -Update Multiple Documents -========================= - -.. 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 f6787bfda..000000000 --- a/source/usage-examples/updateOne.txt +++ /dev/null @@ -1,70 +0,0 @@ -.. _node-usage-updateone: - -================= -Update a Document -================= - -.. 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)