diff --git a/source/faq.txt b/source/faq.txt index 57189d07..5dafd478 100644 --- a/source/faq.txt +++ b/source/faq.txt @@ -134,7 +134,7 @@ and using the ``try_next()`` method to iterate over ``Actor`` instances causes a // Add setup code here let my_coll: Collection = client.database("db").collection("actors"); - let mut cursor = my_coll.find(None, None).await?; + let mut cursor = my_coll.find(doc! {}).await?; while let Some(result) = cursor.try_next().await? { println!("{:?}", result); }; @@ -195,7 +195,7 @@ using the ``?`` operator while handling an insert operation result: .. code-block:: rust :copyable: true - let insert_one_result = my_coll.insert_one(doc, None).await?; + let insert_one_result = my_coll.insert_one(doc).await?; Alternatively, you can create a conditional to handle the unwrapped values of ``InsertOneResult``. The following code uses the ``match`` keyword to process the ``insert_one()`` result: @@ -203,7 +203,7 @@ The following code uses the ``match`` keyword to process the ``insert_one()`` re .. code-block:: rust :copyable: true - let insert_one_result = my_coll.insert_one(doc, None).await; + let insert_one_result = my_coll.insert_one(doc).await; match insert_one_result { Ok(val) => { diff --git a/source/fundamentals/collations.txt b/source/fundamentals/collations.txt index a36576f2..d2dcaf2e 100644 --- a/source/fundamentals/collations.txt +++ b/source/fundamentals/collations.txt @@ -96,10 +96,10 @@ You can define a collation by specifying a collation locale and other options in struct instance. To begin building a ``Collation`` instance, call the ``Collation::builder()`` method. -.. note:: Instantiating Options +.. note:: Instantiating Structs The {+driver-short+} implements the Builder design pattern for the - creation of many different types, including ``Collation``. You can + creation of some struct types, including ``Collation``. You can use the ``builder()`` method to construct an instance of each type by chaining option builder methods. @@ -181,9 +181,9 @@ Set a Collation on a Collection ------------------------------- When you create a new collection, you can define the collation for future operations -called on that collection. Set the collation by using the ``collation()`` function -when creating a ``CreateCollectionOptions`` instance. Then, call the ``create_collection()`` -method with your options instance as a parameter. +called on that collection. Set the collation by chaining the ``collation()`` function +to the ``create_collection()`` method, passing your ``Collation`` instance as a parameter +to ``collation()``. .. _rust-create-collection: @@ -308,9 +308,10 @@ This example performs the following actions: - Sets the ``numeric_ordering`` collation option to ``true``, which ensures that values are sorted in numerical order rather than alphabetical order -- Specifies a collation in a ``FindOptions`` instance, which overrides the collection's collation - Uses the ``find()`` method to return documents in which the value of the ``length`` field is greater than ``"1000"`` +- Specifies a collation by chaining the ``collation()`` method to the ``find()`` method, which overrides + the collection's collation .. io-code-block:: :copyable: true diff --git a/source/fundamentals/crud/compound-operations.txt b/source/fundamentals/crud/compound-operations.txt index 7a87fea0..009b61ac 100644 --- a/source/fundamentals/crud/compound-operations.txt +++ b/source/fundamentals/crud/compound-operations.txt @@ -97,12 +97,11 @@ Modify Find and Delete Behavior ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You can optionally modify the behavior of the ``find_one_and_delete()`` -method by passing a ``FineOneAndDeleteOptions`` instance as a parameter. -To use default values for each setting, specify the value ``None`` for -the options parameter. +method by chaining option builder methods to ``find_one_and_delete()``. These +builder methods set ``FindOneAndDeleteOptions`` struct fields. The following table describes the options available in -``FineOneAndDeleteOptions``: +``FindOneAndDeleteOptions``: .. list-table:: :widths: 30 70 @@ -175,13 +174,15 @@ The following table describes the options available in .. TODO add links to guides for relevant options -The {+driver-short+} implements the Builder design pattern for the -creation of a ``FindOneAndDeleteOptions`` instance. You can use the -type's ``builder()`` method to construct an options instance by -chaining option builder functions one at a time. +.. note:: Setting Options + + You can set ``FindOneAndDeleteOptions`` fields by chaining option builder methods directly + to the ``find_one_and_delete()`` method call. If you're using an earlier version of the driver, + you must construct a ``FindOneAndDeleteOptions`` instance by chaining option builder methods + to the ``builder()`` method. Then, pass your options instance as a parameter to ``find_one_and_delete()``. -The following code shows how to construct a ``FindOneAndDeleteOptions`` -instance and pass it to the ``find_one_and_delete()`` method: +The following code shows how to set the ``comment`` field by chaining +the ``comment()`` method to the ``find_one_and_delete()`` method: .. literalinclude:: /includes/fundamentals/code-snippets/crud/compound.rs :start-after: begin-find-delete-options @@ -236,12 +237,11 @@ Modify Find and Update Behavior ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You can optionally modify the behavior of the ``find_one_and_update()`` -method by passing a ``FindOneAndUpdateOptions`` instance as a parameter. -To use default values for each setting, specify the value ``None`` for -the options parameter. +method by chaining option builder methods to ``find_one_and_update()``. These +builder methods set ``FindOneAndUpdateOptions`` struct fields. The following table describes the options available in -``FineOneAndDeleteOptions``: +``FindOneAndUpdateOptions``: .. list-table:: :widths: 30 70 @@ -343,13 +343,8 @@ The following table describes the options available in .. TODO add link to array updates page under option .. TODO add links to guides for relevant options -The {+driver-short+} implements the Builder design pattern for the -creation of a ``FindOneAndUpdateOptions`` instance. You can use the -type's ``builder()`` method to construct an options instance by -chaining option builder methods one at a time. - -The following code shows how to construct a ``FindOneAndUpdateOptions`` -instance and pass it to the ``find_one_and_update()`` method: +The following code shows how to set the ``comment`` field by chaining +the ``comment()`` method to the ``find_one_and_update()`` method: .. literalinclude:: /includes/fundamentals/code-snippets/crud/compound.rs :start-after: begin-find-update-options @@ -361,15 +356,15 @@ instance and pass it to the ``find_one_and_update()`` method: Find and Update Example ~~~~~~~~~~~~~~~~~~~~~~~ -This example shows how to call the ``find_one_and_update()`` method with the -following parameters: +This example shows how to perform the following actions: -- A query filter that matches a document where the value of ``school`` - is ``"Aurora High School"`` -- An update document that sets the ``school`` field to ``"Durango High School"`` - and increments the ``age`` field by ``1`` -- A ``FindOneAndUpdateOptions`` instance that returns the document - *after* the update +- Call the ``find_one_and_update()`` method +- Pass a query filter to ``find_one_and_update()`` that matches a document where the + value of ``school`` is ``"Aurora High School"`` +- Pass an update document to ``find_one_and_update()`` that sets the ``school`` field to + ``"Durango High School"`` and increments the ``age`` field by ``1`` +- Chain the ``return_document()`` method to ``find_one_and_update()`` to return + the matched document *after* the update .. io-code-block:: :copyable: true @@ -411,9 +406,8 @@ Modify Find and Replace Behavior ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You can optionally modify the behavior of the ``find_one_and_replace()`` -method by passing a ``FindOneAndReplaceOptions`` instance as a parameter. -To use default values for each setting, specify the value ``None`` for -the options parameter. +method by chaining option builder methods to ``find_one_and_replace()``. These +builder methods set ``FindOneAndReplaceOptions`` struct fields. The following table describes the options available in ``FindOneAndReplaceOptions``: @@ -511,14 +505,9 @@ The following table describes the options available in .. TODO add link to array updates page under option .. TODO add links to guides for relevant options - -The {+driver-short+} implements the Builder design pattern for the -creation of a ``FindOneAndReplaceOptions`` instance. You can use the -type's ``builder()`` method to construct an options instance by -chaining option builder functions one at a time. -The following code shows how to construct a ``FindOneAndReplaceOptions`` -instance and pass it to the ``find_one_and_replace()`` method: +The following code shows how to set the ``comment`` field by chaining +the ``comment()`` method to the ``find_one_and_replace()`` method: .. literalinclude:: /includes/fundamentals/code-snippets/crud/compound.rs :start-after: begin-find-replace-options @@ -530,15 +519,17 @@ instance and pass it to the ``find_one_and_replace()`` method: Find and Replace Example ~~~~~~~~~~~~~~~~~~~~~~~~ -This example shows how to call the ``find_one_and_replace()`` method with the -following parameters: - -- A query filter that matches a document where the value of ``name`` - includes the string ``"Johnson"`` -- A replacement document that describes a new student -- A ``FindOneAndReplaceOptions`` instance that returns the document - after replacement and projects only the ``name`` and ``school`` fields - in the output +This example performs the following actions: + +- Calls the ``find_one_and_replace()`` method +- Passes a query filter to ``find_one_and_replace()`` that matches a document + where the value of ``name`` includes the string ``"Johnson"`` +- Passes a replacement document to ``find_one_and_replace()`` that describes a new + student +- Chains the ``return_document()`` method to ``find_one_and_replace()`` to return the document + after replacement +- Chains the ``projection()`` method to ``find_one_and_replace()``to project only the ``name`` + and ``school`` fields in the output .. io-code-block:: :copyable: true diff --git a/source/fundamentals/crud/read-operations/change-streams.txt b/source/fundamentals/crud/read-operations/change-streams.txt index 0fdfd3c6..ca142a47 100644 --- a/source/fundamentals/crud/read-operations/change-streams.txt +++ b/source/fundamentals/crud/read-operations/change-streams.txt @@ -137,8 +137,9 @@ is ``"Wes Anderson"``, the preceding code produces the following output: Apply Aggregation Operators to your Change Stream ------------------------------------------------- -You can pass an aggregation pipeline as a parameter to the ``watch()`` method -to specify which change events the change stream receives. +You can chain the ``pipeline()`` method to the ``watch()`` method +to specify which change events the change stream receives. Pass an +aggregation pipeline as a parameter to ``pipeline()``. To learn which aggregation operators your MongoDB Server version supports, see :ref:`` in the Server manual. @@ -147,7 +148,7 @@ Example ~~~~~~~ The following example creates an aggregation pipeline to filter for update -operations. Then, the code passes the pipeline to the ``watch()`` method, +operations. Then, the code passes the pipeline to the ``pipeline()`` method, configuring the change stream to only receive and print change events for update operations: @@ -222,22 +223,10 @@ must perform the following actions: Create a Collection with Pre-Image and Post-Images Enabled ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -To create a collection with the pre-image and post-image documents enabled, -configure this option in a ``CreateCollectionOptions`` struct instance. To begin -building a ``CreateCollectionOptions`` instance, call the ``CreateCollectionOptions::builder()`` -method. - -.. note:: Instantiating Options - - The {+driver-short+} implements the Builder design pattern for the - creation of many different types, including ``CreateCollectionOptions``. You - can use the ``builder()`` method to construct an instance of each type - by chaining option builder methods. - -When configuring your ``CreateCollectionOptions`` instance, you must use the -``change_stream_pre_and_post_images()`` builder method. The following example -uses this builder method to specify collection options and creates a -collection for which pre- and post-images are available: +To enable pre-image and post-image documents for your collection, use the +``change_stream_pre_and_post_images()`` option builder method. The following example +uses this builder method to specify collection options and creates a collection +for which pre- and post-images are available: .. literalinclude:: /includes/fundamentals/code-snippets/crud/watch.rs :language: rust @@ -262,11 +251,7 @@ Pre-Image Configuration Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To configure a change stream that returns change events containing the pre-image, -specify a ``ChangeStreamOptions`` struct instance. To begin building a ``ChangeStreamOptions`` -instance, call the ``ChangeStreamOptions::builder()`` method. - -When configuring your ``ChangeStreamOptions`` instance to return the pre-image document, -you must use the ``full_document_before_change()`` builder method. The following example +use the ``full_document_before_change()`` option builder method. The following example specifies change stream options and creates a change stream that returns pre-image documents: @@ -277,7 +262,7 @@ documents: :end-before: end-pre The preceding example passes a value of ``FullDocumentBeforeChangeType::Required`` -to the ``full_document_before_change()`` builder method. This option configures the change +to the ``full_document_before_change()`` option builder method. This method configures the change stream to require pre-images for replace, update, and delete change events. If the pre-image is not available, the driver raises an error. @@ -297,11 +282,7 @@ Post-Image Configuration Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To configure a change stream that returns change events containing the post-image, -specify a ``ChangeStreamOptions`` struct instance. To begin building a ``ChangeStreamOptions`` -instance, call the ``ChangeStreamOptions::builder()`` method. - -When configuring your ``ChangeStreamOptions`` instance to return the post-image document, -you must use the ``full_document()`` builder method. The following example specifies change +use the ``full_document()`` option builder method. The following example specifies change stream options and creates a change stream that returns post-image documents: .. literalinclude:: /includes/fundamentals/code-snippets/crud/watch.rs @@ -311,8 +292,8 @@ stream options and creates a change stream that returns post-image documents: :end-before: end-post The preceding example passes a value of ``FullDocument::WhenAvailable`` to the ``full_document()`` -builder method. This option configures the change stream to return post-images for replace, update, -and delete change events if the post-image is available. +option builder method. This method configures the change stream to return post-images for replace, +update, and delete change events if the post-image is available. If you delete the document in which the value of ``name`` is ``"Todd Haynes"``, the change event produces the following output: diff --git a/source/fundamentals/crud/read-operations/cursor.txt b/source/fundamentals/crud/read-operations/cursor.txt index 50423a6c..7de416d7 100644 --- a/source/fundamentals/crud/read-operations/cursor.txt +++ b/source/fundamentals/crud/read-operations/cursor.txt @@ -242,20 +242,20 @@ You can use the following methods to retrieve documents as an array: Specify Cursor Behavior ----------------------- -To modify the cursor that an operation returns, pass options to +To modify the cursor that an operation returns, chain option builder methods to the method that returns the ``Cursor`` instance. For example, you can -specify cursor-related options in a ``FindOptions`` type that you pass to the -``find()`` method. +chain cursor-related option builder methods to the ``find()`` method. -.. note:: Instantiating Options +.. note:: Setting Options - The {+driver-short+} implements the Builder design pattern for the - creation of many different types, including ``FindOptions``. You can - use each type's ``builder()`` method to construct an options instance - by chaining option builder functions one at a time. + You can set ``FindOptions`` fields by chaining option builder methods directly + to the ``find()`` method call. If you're using an earlier version of the + driver, you must construct a ``FindOptions`` instance by chaining option + builder methods to the ``builder()`` method. Then, pass your ``FindOptions`` + instance as a parameter to ``find()``. -The following table describes cursor-related options that you can set in -an options instance: +The following table describes cursor-related options that you can set by +calling their corresponding builder method: .. list-table:: :widths: 30 70 @@ -298,8 +298,8 @@ an options instance: | Type: ``bool`` | Default: ``false`` -The following code shows how to construct a ``FindOptions`` -instance and specify cursor-related settings: +The following code shows how to specify cursor-related settings by chaining +option builder methods to the ``find()`` method: .. literalinclude:: /includes/fundamentals/code-snippets/crud/cursor.rs :start-after: start-options diff --git a/source/fundamentals/crud/read-operations/retrieve.txt b/source/fundamentals/crud/read-operations/retrieve.txt index 6ece6f4c..fa60d44d 100644 --- a/source/fundamentals/crud/read-operations/retrieve.txt +++ b/source/fundamentals/crud/read-operations/retrieve.txt @@ -104,21 +104,18 @@ the :ref:`find_one() example `. Modify Find Behavior ~~~~~~~~~~~~~~~~~~~~ -You can modify the behavior of ``find()`` by passing -a ``FindOptions`` instance as a parameter, and you can modify the -behavior of ``find_one()`` by passing a ``FindOneOptions`` instance. +You can modify the behavior of the ``find()`` method by chaining ``FindOptions`` +option builder methods to ``find()``, and you can modify the behavior of the ``find_one()`` +method by chaining ``FindOneOptions`` option builder methods to ``find_one()``. -To use default values for each setting, specify the value ``None`` as -the options parameter. - -The following table describes commonly used settings that you can specify in -``FindOptions`` and ``FindOneOptions``: +The following table describes commonly used ``FindOptions`` and ``FindOneOptions`` +fields that you can set by calling their corresponding builder methods: .. list-table:: :widths: 30 70 :header-rows: 1 - * - Setting + * - Field - Description * - ``collation`` @@ -170,13 +167,13 @@ The following table describes commonly used settings that you can specify in .. TODO link to skip fundamentals page under skip setting .. TODO link to sort fundamentals page under sort setting -.. note:: Instantiating Options +.. note:: Setting Options - The {+driver-short+} implements the Builder design pattern for the - creation of many different types, such as ``FindOneOptions`` or - ``FindOptions``. You can use each type's ``builder()`` method to - construct an options instance by chaining option builder functions - one at a time. + You can set ``FindOptions`` and ``FindOneOptions`` fields by chaining option builder methods + directly to the find operation method call. If you're using an earlier version of the driver, + you must construct a ``FindOptions`` or ``FindOneOptions`` instance by chaining option builder + methods to the ``builder()`` method. Then, pass your options instance as a parameter to + ``find()`` or ``find_one()``. For a full list of settings you can specify for each type, see the API documentation for `FindOptions @@ -195,12 +192,12 @@ criteria. find() Example `````````````` -This example shows how to call the ``find()`` method with the -following parameters: +This example performs the following actions: -- A query filter that matches documents where the value of ``unit_price`` +- Calls the ``find()`` method +- Passes a query filter to ``find()`` that matches documents where the value of ``unit_price`` is less than ``12.00`` and the value of ``category`` is not ``"kitchen"`` -- A ``FindOptions`` instance that sorts matched documents by +- Chains the ``sort()`` method to ``find()`` to sort matched documents by ``unit_price`` in descending order .. io-code-block:: @@ -224,12 +221,12 @@ following parameters: find_one() Example `````````````````` -This example shows how to call the ``find_one()`` method with the -following parameters: +This example performs the following actions: -- A query filter that matches documents where the value of ``unit_price`` - is less than or equal to ``20.00`` -- A ``FindOneOptions`` instance that skips the first two matched documents +- Calls the ``find_one()`` method +- Passes a query filter to ``find_one()`` that matches documents where the value of + ``unit_price`` is less than or equal to ``20.00`` +- Chains the ``skip()`` method to ``find_one()`` to skip the first two matched documents .. io-code-block:: :copyable: true @@ -279,20 +276,17 @@ all the documents in the collection. Modify Aggregation Behavior ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -You can modify the behavior of ``aggregate()`` by passing -an ``AggregateOptions`` instance as an optional parameter. - -To use default values for each setting, specify the value ``None`` as -the options parameter. +You can modify the behavior of the ``aggregate()`` method by chaining +``AggregateOptions`` option builder methods to ``aggregate()``. -The following table describes commonly used settings that you can specify in -``AggregateOptions``: +The following table describes commonly used ``AggregateOptions`` fields +that you can set by calling their corresponding builder methods: .. list-table:: :widths: 30 70 :header-rows: 1 - * - Setting + * - Field - Description * - ``allow_disk_use`` diff --git a/source/fundamentals/crud/write-operations/change.txt b/source/fundamentals/crud/write-operations/change.txt index 873334b0..88ab484d 100644 --- a/source/fundamentals/crud/write-operations/change.txt +++ b/source/fundamentals/crud/write-operations/change.txt @@ -60,7 +60,6 @@ These methods take the following parameters: - A query filter to match one or more documents to change - An update document that specifies the field and value changes -- *(Optional)* An options type to modify the default behavior of the method The {+driver-short+} provides the following methods to change documents: @@ -93,6 +92,10 @@ You can perform update operations with the following methods: - ``update_many()``, which updates all documents that match the search criteria +You can also chain option builder methods to these update operation methods. To learn about +modifying the behavior of the update methods, see the :ref:`Modify Update and Replace Behavior +` section of this guide. + Parameters ~~~~~~~~~~ @@ -127,10 +130,6 @@ and descriptions `. :manual:`updates with aggregation pipelines `. -Update operations also take an ``UpdateOptions`` parameter. To learn -about modifying the behavior of the update methods, see the :ref:`Modify -Update and Replace Behavior ` section of this guide. - Return Value ~~~~~~~~~~~~ @@ -302,6 +301,10 @@ You can perform a replace operation with the ``replace_one()`` method. This method replaces all existing fields of a document except for the ``_id`` field with new fields and values that you specify. +You can also chain option builder methods to a replace operation method. To learn +about modifying the behavior of the ``replace_one()`` method, see the :ref:`Modify +Update and Replace Behavior ` section of this guide. + Parameters ~~~~~~~~~~ @@ -313,10 +316,6 @@ existing document. Replacement documents use the following format: doc! { "": , "": , ... } -Replace operations also take an ``UpdateOptions`` parameter. To learn -about modifying the behavior of the ``replace_one()`` method, see the :ref:`Modify -Update and Replace Behavior ` section of this guide. - Return Values ~~~~~~~~~~~~~ @@ -404,15 +403,16 @@ Modify Update and Replace Behavior ---------------------------------- You can modify the behavior of the ``update_one()``, ``update_many``, -and ``replace_one()`` methods by constructing and passing an -``UpdateOptions`` struct as a parameter. +and ``replace_one()`` methods by calling options methods that set +``UpdateOptions`` struct fields. -.. note:: Instantiating Options +.. note:: Setting Options - The {+driver-short+} implements the Builder design pattern for the - creation of many different types, including ``UpdateOptions``. You - can use each type's ``builder()`` method to construct an options - instance by chaining option builder functions one at a time. + You can set ``UpdateOptions`` fields by chaining option builder methods directly + to the update or replace method call. If you're using an earlier version of the driver, + you must construct an ``UpdateOptions`` instance by chaining option builder methods + to the ``builder()`` method. Then, pass your options instance as a parameter to + ``update_one()``, ``update_many``, or ``replace_one()``. The following table describes the options available in ``UpdateOptions``: @@ -484,8 +484,8 @@ The following table describes the options available in ``UpdateOptions``: .. TODO add links to guides for relevant options -The following code shows how to construct an ``UpdateOptions`` -instance and pass it to the ``update_one()`` method: +The following code shows how to set the ``upsert`` field by chaining +the ``upsert()`` method to the ``update_one()`` method: .. literalinclude:: /includes/fundamentals/code-snippets/crud/change.rs :start-after: begin-options diff --git a/source/fundamentals/crud/write-operations/delete.txt b/source/fundamentals/crud/write-operations/delete.txt index e9183257..f8e9467e 100644 --- a/source/fundamentals/crud/write-operations/delete.txt +++ b/source/fundamentals/crud/write-operations/delete.txt @@ -66,20 +66,22 @@ The ``delete_one()`` and ``delete_many()`` methods take a query filter as a parameter. A query filter consists of the fields and values that form criteria for documents to match. -You can also optionally pass a ``DeleteOptions`` type as a parameter to -either method. You can specify settings in a ``DeleteOptions`` instance -to configure the delete operation. To use default values for each -setting, specify the value ``None`` as the options parameter. +Options +~~~~~~~ -.. note:: Instantiating Options +You can modify the behavior of the delete operation methods by chaining +option builder methods to ``delete_one()`` and ``delete_many()``. These option +methods set ``DeleteOptions`` struct fields. + +.. note:: Setting Options - The {+driver-short+} implements the Builder design pattern for the - creation of many different types, including ``DeleteOptions``. You - can use each type's ``builder()`` method to construct an options - instance by chaining option builder functions one at a time. + You can set ``DeleteOptions`` fields by chaining option builder methods directly + to the delete method call. If you're using an earlier version of the driver, + you must construct an ``DeleteOptions`` instance by chaining option builder methods + to the ``builder()`` method. Then, pass your options instance as a parameter to + ``delete_one()`` or ``delete_many()``. -The following table describes settings that you can specify in a -``DeleteOptions`` instance: +The following table describes the options available in ``DeleteOptions``: .. list-table:: :header-rows: 1 @@ -131,8 +133,8 @@ The following table describes settings that you can specify in a .. TODO add links to guides for relevant options -The following code shows how to construct an ``DeleteOptions`` -instance and pass it to the ``delete_one()`` method: +The following code shows how to set the ``comment`` field by chaining +the ``comment()`` method to the ``delete_one()`` method: .. literalinclude:: /includes/fundamentals/code-snippets/crud/delete.rs :start-after: begin-options @@ -153,14 +155,15 @@ not remove any documents, and the value of ``deleted_count`` is ``0``. delete_many() Example ~~~~~~~~~~~~~~~~~~~~~ -This example shows how to call the ``delete_many()`` method with the -following parameters: +This example performs the following actions: -- A query filter that matches documents where the value of ``category`` +- Calls the ``delete_many()`` method +- Passes a query filter to ``delete_many()`` that matches documents where the value of ``category`` is ``"garden"`` -- A ``DeleteOptions`` instance that uses the ``_id_`` index as the hint +- Chains the ``hint()`` method to ``delete_many()`` to use the ``_id_`` index as the hint for the delete operation + .. io-code-block:: .. input:: /includes/fundamentals/code-snippets/crud/delete.rs diff --git a/source/fundamentals/crud/write-operations/insert.txt b/source/fundamentals/crud/write-operations/insert.txt index dbae224f..f5ad2b9f 100644 --- a/source/fundamentals/crud/write-operations/insert.txt +++ b/source/fundamentals/crud/write-operations/insert.txt @@ -107,15 +107,17 @@ document into the ``books`` collection: Modify insert_one Behavior ~~~~~~~~~~~~~~~~~~~~~~~~~~ -You can modify the behavior of the ``insert_one()`` method by -constructing and passing an ``InsertOneOptions`` struct. +You can modify the behavior of the ``insert_one()`` method by chaining option +builder methods to ``insert_one()``. These option builder methods set ``InsertOneOptions`` +struct fields. -.. note:: Instantiating Options +.. note:: Setting Options - The {+driver-short+} implements the Builder design pattern for the - creation of many different types, including ``InsertOneOptions``. - You can use each type's ``builder()`` method to construct an options - instance by chaining option builder functions one at a time. + You can set ``InsertOneOptions`` fields by chaining option builder methods directly + to the ``insert_one()`` method call. If you're using an earlier version of the + driver, you must construct an ``InsertOneOptions`` instance by chaining option builder + methods to the ``builder()`` method. Then, pass your options instance as a parameter + to ``insert_one()``. The following table describes the options available in ``InsertOneOptions``: @@ -155,8 +157,9 @@ The following table describes the options available in ``InsertOneOptions``: .. _rust-insertone-bypass-validation-ex: -The following code shows how to construct an ``InsertOneOptions`` -instance: +The following code shows how to set the ``bypass_document_validation`` field +by chaining the ``bypass_document_validation()`` method to the ``insert_one()`` +method: .. literalinclude:: /includes/fundamentals/code-snippets/crud/insert.rs :start-after: begin-one-options @@ -206,10 +209,11 @@ multiple documents into the ``books`` collection: Modify insert_many Behavior ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -You can modify the behavior of the ``insert_many()`` method by -constructing and passing an ``InsertManyOptions`` struct. The -following table describes the options available in -``InsertManyOptions``: +You can modify the behavior of the ``insert_many()`` method by chaining +option builder methods to ``insert_many()``. These option builder methods set ``InsertManyOptions`` +struct fields. + +The following table describes the options available in ``InsertManyOptions``: .. list-table:: :header-rows: 1 @@ -256,8 +260,9 @@ following table describes the options available in | Type: ``Bson`` | Default: ``None`` -The following code shows how to construct an ``InsertManyOptions`` -instance: +The following code shows how to set the ``comment`` field by +chaining the ``comment()`` method to the ``insert_many()`` +method: .. literalinclude:: /includes/fundamentals/code-snippets/crud/insert.rs :start-after: begin-many-options @@ -283,14 +288,14 @@ collection: { "_id": 3, "title": "Goodnight Moon" } When you attempt to insert these documents, the result depends on the -value of the ``ordered`` option in your ``InsertManyOptions``: +value passed to the ``ordered()`` option builder method: -- If ``ordered`` is ``true`` (the default value), the driver throws a +- If you pass a value of ``true`` (the default value), the driver throws a ``BulkWriteError`` when it attempts to insert the document with the duplicate ``_id`` value. However, the driver still inserts the documents before the error occurs. -- If you set ``ordered`` to ``false``, the driver still throws a +- If you pass a value of ``false``, the driver still throws a ``BulkWriteError`` when it attempts to insert the document with the duplicate ``_id`` value, but it inserts every other document. diff --git a/source/fundamentals/database-collection.txt b/source/fundamentals/database-collection.txt index c24f6bde..f0434118 100644 --- a/source/fundamentals/database-collection.txt +++ b/source/fundamentals/database-collection.txt @@ -199,10 +199,8 @@ Create a Collection You can explicitly create a collection by calling the `create_collection() <{+api+}/struct.Database.html#method.create_collection>`__ method on a -``Database`` instance. This method takes the collection name and an -optional `CreateCollectionOptions -<{+api+}/options/struct.CreateCollectionOptions.html>`__ type as -parameters. You can use a ``Collection`` instance to perform data +``Database`` instance. This method takes the collection name as +a parameter. You can use a ``Collection`` instance to perform data operations, create aggregations, and manage indexes. The following code shows how to create a collection called ``coll_abc`` diff --git a/source/fundamentals/gridfs.txt b/source/fundamentals/gridfs.txt index 2e268950..38cd7d02 100644 --- a/source/fundamentals/gridfs.txt +++ b/source/fundamentals/gridfs.txt @@ -113,19 +113,18 @@ creates a reference to either a new or existing GridFS bucket: :copyable: :dedent: -You can specify a custom bucket name and other options in a ``GridFsBucketOptions`` -struct instance. To begin building a ``GridFsBucketOptions`` instance, call the -``GridFsBucketOptions::builder()`` method. +You can specify a custom bucket name by setting the ``bucket_name`` field of the +``GridFsBucketOptions`` struct. -.. note:: Instantiating Options +.. note:: Instantiating Structs The {+driver-short+} implements the Builder design pattern for the - creation of many different types, including ``GridFsBucketOptions``. You - can use the ``builder()`` method to construct an instance of each type + creation of some struct types, including ``GridFsBucketOptions``. You can + use the ``builder()`` method to construct an instance of each type by chaining option builder methods. -The following table describes the builder methods that you can use to set fields of a -``GridFsBucketOptions`` instance: +The following table describes the methods that you can use to set ``GridFsBucketOptions`` +fields: .. list-table:: :widths: 1 1 2 @@ -164,8 +163,8 @@ The following table describes the builder methods that you can use to set fields - | Specifies which servers are suitable for a bucket operation, which is set to the database's selection | criteria by default -The following example specifies options in a ``GridFsBucketOptions`` instance to configure a custom -bucket name and a five-second time limit for write operations: +The following example specifies options in a ``GridFsBucketOptions`` instance to configure +a custom bucket name and a five-second time limit for write operations: .. literalinclude:: /includes/fundamentals/code-snippets/gridfs.rs :start-after: start-create-opts diff --git a/source/fundamentals/indexes.txt b/source/fundamentals/indexes.txt index 64bcd5a5..de804c16 100644 --- a/source/fundamentals/indexes.txt +++ b/source/fundamentals/indexes.txt @@ -262,10 +262,10 @@ To create a clustered collection, perform the following steps: 1. Create a ``ClusteredIndex`` instance. -#. Set the ``ClusteredIndex`` instance as the value of the - ``clustered_index`` field of a ``CreateCollectionOptions`` instance. +#. Call the ``create_collection()`` method. -#. Pass the options to the ``create_collection()`` method. +#. Chain the ``clustered_index()`` method to the ``create_collection()`` method, + passing your ``ClusteredIndex`` instance as a parameter of ``clustered_index()``. You must set the following fields of the ``ClusteredIndex`` struct: diff --git a/source/fundamentals/indexes/atlas-search-indexes.txt b/source/fundamentals/indexes/atlas-search-indexes.txt index 59dc8396..ab13d979 100644 --- a/source/fundamentals/indexes/atlas-search-indexes.txt +++ b/source/fundamentals/indexes/atlas-search-indexes.txt @@ -55,7 +55,7 @@ call the ``SearchIndexModel::builder()`` method. .. note:: Instantiating Models The {+driver-short+} implements the Builder design pattern for the - creation of many different types, including ``SearchIndexModel``. You + creation of some struct types, including ``SearchIndexModel``. You can use the ``builder()`` method to construct an instance of each type by chaining option builder methods. @@ -94,11 +94,8 @@ Create a Search Index --------------------- You can create an Atlas Search index on a collection by calling the ``create_search_index()`` -method on a ``Collection`` instance. This method accepts the following parameters: - -- Index model, specified in a ``SearchIndexModel`` instance -- Index options, specified in a `CreateSearchIndexOptions - <{+api+}/options/struct.CreateSearchIndexOptions.html>`__ instance +method on a ``Collection`` instance. This method accepts an index model as a parameter, specified +in a ``SearchIndexModel`` instance. Example ~~~~~~~ @@ -130,10 +127,8 @@ Create Multiple Search Indexes ------------------------------ You can create multiple Atlas Search indexes at once by calling the ``create_search_indexes()`` -method on a ``Collection`` instance. This method accepts the following parameters: - -- List of index models, specified as a vector of ``SearchIndexModel`` instances -- Index options, specified in a ``CreateSearchIndexOptions`` instance +method on a ``Collection`` instance. This method accepts a list of index models as a parameter, +specified as a vector of ``SearchIndexModel`` instances. Example ~~~~~~~ @@ -166,23 +161,15 @@ List Search Indexes ------------------- You can access information about a collection's existing Atlas Search indexes -by calling the ``list_search_indexes()`` method on the collection. This -method accepts the following parameters: - -- Name of the index to retrieve information about -- Aggregation options, specified in an `AggregateOptions - <{+api+}/options/struct.AggregateOptions.html>`__ instance -- Index options, specified in a `ListSearchIndexOptions - <{+api+}/options/struct.ListSearchIndexOptions.html>`__ instance +by calling the ``list_search_indexes()`` method on the collection. Example ~~~~~~~ The following example accesses information about the Atlas Search indexes created in the :ref:`rust-create-search-indexes` section of this page. The code calls the -``list_search_indexes()`` method and passes a value of ``None`` for each parameter, -which instructs the driver to return information about all Atlas Search indexes with -default options. Then, the code outputs the search indexes: +``list_search_indexes()`` method and outputs all the Atlas Search indexes on the +collection: .. io-code-block:: :copyable: true @@ -218,8 +205,6 @@ method on a ``Collection`` instance. This method accepts the following parameter - Name of the index to update - Modified index definition document -- Index options, specified in an `UpdateSearchIndexOptions - <{+api+}/options/struct.UpdateSearchIndexOptions.html>`__ instance Example ~~~~~~~ @@ -242,11 +227,8 @@ Delete a Search Index --------------------- You can delete an Atlas Search index by calling the ``delete_search_index()`` -method on a ``Collection`` instance. This method accepts the following parameters: - -- Name of the index to delete -- Index options, specified in a `DropSearchIndexOptions - <{+api+}/options/struct.DropSearchIndexOptions.html>`__ instance +method on a ``Collection`` instance. This method accepts the name of the index to delete +as a parameter. Example ~~~~~~~ diff --git a/source/fundamentals/run-command.txt b/source/fundamentals/run-command.txt index 30a85805..40448cab 100644 --- a/source/fundamentals/run-command.txt +++ b/source/fundamentals/run-command.txt @@ -67,7 +67,7 @@ the current member's role in the replica set, on a database: .. code-block:: rust - let result = my_db.run_command(doc! { "hello": 1 }, None).await?; + let result = my_db.run_command(doc! { "hello": 1 }).await?; The ``checkMetadataConsistency`` command returns multiple result documents. You can use the ``run_cursor_command()`` method to run @@ -76,7 +76,7 @@ this command and collect the results, as shown in the following code: .. code-block:: rust let cursor = my_db - .run_cursor_command(doc! { "checkMetadataConsistency": 1 }, None) + .run_cursor_command(doc! { "checkMetadataConsistency": 1 }) .await?; To find a link to a full list of database commands and corresponding @@ -90,21 +90,21 @@ parameters, see the :ref:`Additional Information section object elsewhere in your code. By default, they use the ``primary`` read preference. - You can set a read preference for command execution by - passing an options object to either method. The following code shows - how to specify a read preference in a ``SelectionCriteria`` instance - and pass it as an option to the ``run_command()`` method: + You can set a read preference for command execution by chaining + the ``selection_criteria()`` method to ``run_command()`` or ``run_cursor_command()``. + The following code shows how to specify a read preference in a + ``SelectionCriteria`` instance and pass it as a parameter to the + ``selection_criteria()`` method: .. code-block:: rust - let command_options = SelectionCriteria::ReadPreference( - ReadPreference::Primary - ); - let result = my_db.run_command(command_doc, command_options).await?; + let result = my_db + .run_command(doc! { "hello": 1 }) + .selection_criteria(SelectionCriteria::ReadPreference(ReadPreference::Primary)) + .await?; - The ``run_cursor_command()`` method takes a - ``RunCursorCommandOptions`` instance as a parameter. You can set the - ``selection_criteria`` field of this struct to select a read preference. + To set a read preference for the ``run_cursor_command()`` method, use the + same syntax as the preceding example. For more information on read preference options, see :manual:`Read Preference ` in the Server manual. diff --git a/source/fundamentals/schema-validation.txt b/source/fundamentals/schema-validation.txt index 2a34ccb3..e9e5c592 100644 --- a/source/fundamentals/schema-validation.txt +++ b/source/fundamentals/schema-validation.txt @@ -54,19 +54,17 @@ Implement Schema Validation --------------------------- You can implement schema validation by passing your schema and related options -in an instance of ``CreateCollectionOptions`` to the ``create_collection()`` -method. You can build a ``CreateCollectionOptions`` instance by using the -``CreateCollectionOptions::builder()`` method. +to the ``CreateCollectionOptions`` option builder methods. -.. note:: Instantiating Options +.. note:: Setting Options - The {+driver-short+} implements the Builder design pattern for the - creation of many different types, including ``CreateCollectionOptions``. - You can use each type's ``builder()`` method to construct an options - instance by chaining option builder functions one at a time. + You can set ``CreateCollectionOptions`` fields by chaining option builder methods + directly to the ``create_collection()`` method call. If you're using an earlier + version of the driver, you must construct a ``CreateCollectionOptions`` instance by + chaining option builder methods to the ``builder()`` method. -Call the following ``CreateCollectionOptions::builder()`` functions to specify -the validation options for the new collection: +Call the following ``CreateCollectionOptions`` methods to specify the validation +options for the new collection: .. list-table:: :widths: 30 70 diff --git a/source/fundamentals/stable-api.txt b/source/fundamentals/stable-api.txt index 6202ca9b..e492d805 100644 --- a/source/fundamentals/stable-api.txt +++ b/source/fundamentals/stable-api.txt @@ -82,10 +82,10 @@ in the ``ServerApi`` struct. While you can set the fields in a ``ServerApi`` struct manually, you can use the builder design pattern to define the struct more efficiently. -.. note:: Instantiating Options +.. note:: Setting Options The {+driver-short+} implements the Builder design pattern for the - creation of many different types, including the ``ServerApi`` struct. + creation of some struct types, including the ``ServerApi`` struct. You can use each type's ``builder()`` method to construct an options instance by chaining option builder functions one at a time. diff --git a/source/fundamentals/time-series.txt b/source/fundamentals/time-series.txt index c44d4101..72e0cf8d 100644 --- a/source/fundamentals/time-series.txt +++ b/source/fundamentals/time-series.txt @@ -70,19 +70,17 @@ Create a Time Series Collection To create and interact with time series collections, you must be connected to a deployment running MongoDB 5.0 or later. - To create a time series collection, perform the following actions: 1. Create a ``TimeseriesOptions`` instance that specifies properties of your time series collection. -#. Create a ``CreateCollectionOptions`` instance and set the value of - the ``timeseries`` field to your ``TimeseriesOptions`` instance. - -#. Pass the ``CreateCollectionOptions`` instance to the - ``create_collection()`` method. You must also pass the collection +#. Call the ``create_collection()`` method and pass the collection name as a parameter. +#. Chain the ``timeseries()`` method to the ``create_collection()`` method. + Pass your ``TimeseriesOptions`` instance as a parameter to ``timeseries()``. + Example ~~~~~~~ diff --git a/source/fundamentals/transactions.txt b/source/fundamentals/transactions.txt index 118d00cc..66c82a17 100644 --- a/source/fundamentals/transactions.txt +++ b/source/fundamentals/transactions.txt @@ -64,17 +64,17 @@ describes these methods: - Description * - ``start_transaction()`` - - | Starts a new transaction, configured according to an optional - ``TransactionOptions`` parameter, on this session. The session + - | Starts a new transaction on this session. The session must be passed into each operation within the transaction, or the operation will run outside of the transaction. | + | You can set transaction options by chaining ``TransactionOptions`` + option builder methods to ``start_transaction()``. + | | Errors returned from operations run within the transaction might include a ``TRANSIENT_TRANSACTION_ERROR`` label, which indicates that the entire transaction can be ended, then retried with the expectation that it will succeed. - | - | **Parameter**: ``TransactionOptions`` * - ``commit_transaction()`` - | Commits the active transaction for this session. This method returns an @@ -93,30 +93,29 @@ describes these methods: error if there is no active transaction for the session or if the transaction was committed or ended. - * - ``with_transaction()`` - - | Starts a transaction on this session and runs the given - callback, then commits or ends the transaction. When you use - this method to perform a transaction, the driver automatically + * - ``and_run()`` + - | Runs the given callback, then commits or ends the transaction. When you + use this method to perform a transaction, the driver automatically handles any errors, so you can choose to omit error handling code. | | Because the callback returns a future and can be run multiple times, the Rust language closure borrowing rules for captured - values can be restrictive. So, the ``with_transaction()`` + values can be restrictive. So, the ``and_run()`` method accepts a context parameter that is passed to the callback. | | **Parameters**: context ``C``, callback ``FnMut(&'a mut - ClientSession, &'a mut C)``, ``TransactionOptions`` + ClientSession, &'a mut C)`` .. important:: Methods That Can Run in Transactions - To run MongoDB tasks within transactions, you must use the - ``_with_session()`` suffixed methods. These methods accept a + To run MongoDB operations within transactions, you must chain the + ``session()`` method to the operation. This method accepts a ``ClientSession`` instance as a parameter. For example, to delete a document, you can generally use the ``delete_one()`` method. However, to delete a document within - a transaction, you must use the ``delete_one_with_session()`` - method and pass the session as a parameter. + a transaction, you must chain the ``session()`` method to + ``delete_one()`` and pass the session as a parameter. Example ------- @@ -134,8 +133,9 @@ The following code completes the following actions to perform the transaction: 1. Creates a session from the client by using the ``start_session()`` method. -#. Uses the ``with_transaction()`` method to start a transaction and run - the ``insert_media()`` callback function within the transaction. +#. Calls the ``start_transaction()`` method to start a transaction. +#. Calls the ``and_run()`` method to run the ``insert_media()`` callback function + within the transaction. .. io-code-block:: @@ -183,5 +183,5 @@ guide, see the following API documentation: - `start_transaction() <{+api+}/struct.ClientSession.html#method.start_transaction>`__ - `commit_transaction() <{+api+}/struct.ClientSession.html#method.commit_transaction>`__ - `abort_transaction() <{+api+}/struct.ClientSession.html#method.abort_transaction>`__ -- `with_transaction() <{+api+}/struct.ClientSession.html#method.with_transaction>`__ +- `and_run() <{+api+}/struct.ClientSession.html#method.and_run>`__ - `TransactionOptions <{+api+}/options/struct.TransactionOptions.html>`__ \ No newline at end of file diff --git a/source/includes/figures/change_diagram.png b/source/includes/figures/change_diagram.png index 3082a262..211ad6de 100644 Binary files a/source/includes/figures/change_diagram.png and b/source/includes/figures/change_diagram.png differ diff --git a/source/includes/fundamentals/code-snippets/aggregation.rs b/source/includes/fundamentals/code-snippets/aggregation.rs index 4927b757..16d898a5 100644 --- a/source/includes/fundamentals/code-snippets/aggregation.rs +++ b/source/includes/fundamentals/code-snippets/aggregation.rs @@ -26,7 +26,7 @@ async fn main() -> mongodb::error::Result<()> { doc! { "name": "Arthur Ray", "age": 66, "genre_interests": vec!["sci-fi", "fantasy", "fiction"], "last_active": DateTime::builder().year(2023).month(11).day(27).build().unwrap() } ]; - my_coll.insert_many(docs, None).await?; + my_coll.insert_many(docs).await?; // end-insert // begin-age-agg @@ -40,10 +40,10 @@ async fn main() -> mongodb::error::Result<()> { } } ]; - let mut results = my_coll.aggregate(age_pipeline, None).await?; + let mut results = my_coll.aggregate(age_pipeline).await?; while let Some(result) = results.try_next().await? { - let doc = bson::from_document(result)?; - println!("* {}", doc); + let doc = mongodb::bson::from_document(result)?; + println!("* {:?}", doc); } // end-age-agg @@ -55,10 +55,10 @@ async fn main() -> mongodb::error::Result<()> { doc! { "$sort": { "_id.month_last_active" : 1 } } ]; - let mut results = my_coll.aggregate(last_active_pipeline, None).await?; + let mut results = my_coll.aggregate(last_active_pipeline).await?; while let Some(result) = results.try_next().await? { - let doc = bson::from_document(result)?; - println!("* {}", doc); + let doc = mongodb::bson::from_document(result)?; + println!("* {:?}", doc); } // end-lastactive-agg @@ -70,12 +70,13 @@ async fn main() -> mongodb::error::Result<()> { doc! { "$limit": 3 } ]; - let mut results = my_coll.aggregate(popularity_pipeline, None).await?; + let mut results = my_coll.aggregate(popularity_pipeline).await?; while let Some(result) = results.try_next().await? { - let doc = bson::from_document(result)?; - println!("* {}", doc); + let doc = mongodb::bson::from_document(result)?; + println!("* {:?}", doc); } // end-popular-agg Ok(()) } + diff --git a/source/includes/fundamentals/code-snippets/collation.rs b/source/includes/fundamentals/code-snippets/collation.rs index 48348a3c..b87731bc 100644 --- a/source/includes/fundamentals/code-snippets/collation.rs +++ b/source/includes/fundamentals/code-snippets/collation.rs @@ -21,7 +21,7 @@ async fn main() -> mongodb::error::Result<()> { doc! {"name" : "Cryptonomicon", "length" : "918"}, doc! {"name" : "Ça", "length" : "1138"} ]; - let result = my_coll.insert_many(docs, None).await?; + let result = my_coll.insert_many(docs).await?; // start-collation let collation = Collation::builder() @@ -35,16 +35,14 @@ async fn main() -> mongodb::error::Result<()> { .strength(CollationStrength::Primary) .build(); - let opts = CreateCollectionOptions::builder() + let result = my_db.create_collection("books") .collation(collation) - .build(); - - let result = my_db.create_collection("books", opts).await?; + .await?; // end-create-collection // start-default-query let query = doc! { "name": doc! { "$lt": "Infinite Jest" } }; - let mut cursor = my_coll.find(query, None).await?; + let mut cursor = my_coll.find(query).await?; while let Some(doc) = cursor.try_next().await? { println!("{}", doc); @@ -65,7 +63,7 @@ async fn main() -> mongodb::error::Result<()> { .options(index_opts) .build(); - let result = my_coll.create_index(index, None).await?; + let result = my_coll.create_index(index).await?; println!("Created index: {}", result.index_name); // end-index @@ -74,13 +72,11 @@ async fn main() -> mongodb::error::Result<()> { .locale("en_US") .numeric_ordering(true) .build(); - - let opts = FindOptions::builder() - .collation(collation) - .build(); let filter = doc! { "length": doc! { "$gt": "1000" } }; - let mut cursor = my_coll.find(filter, opts).await?; + let mut cursor = my_coll.find(filter) + .collation(collation) + .await?; while let Some(result) = cursor.try_next().await? { println!("{}", result); diff --git a/source/includes/fundamentals/code-snippets/connection-async.rs b/source/includes/fundamentals/code-snippets/connection-async.rs index 14c12b78..ec79ae6f 100644 --- a/source/includes/fundamentals/code-snippets/connection-async.rs +++ b/source/includes/fundamentals/code-snippets/connection-async.rs @@ -14,7 +14,7 @@ async fn main() -> mongodb::error::Result<()> { let client = Client::with_options(client_options)?; // Send a ping to confirm a successful connection - client.database("admin").run_command(doc! { "ping": 1 }, None).await?; + client.database("admin").run_command(doc! { "ping": 1 }).await?; println!("Pinged your deployment. You successfully connected to MongoDB!"); Ok(()) diff --git a/source/includes/fundamentals/code-snippets/connection-sync.rs b/source/includes/fundamentals/code-snippets/connection-sync.rs index 7f25039f..b4860846 100644 --- a/source/includes/fundamentals/code-snippets/connection-sync.rs +++ b/source/includes/fundamentals/code-snippets/connection-sync.rs @@ -13,7 +13,7 @@ fn main() -> mongodb::error::Result<()> { let client = Client::with_options(client_options)?; // Send a ping to confirm a successful connection - client.database("admin").run_command(doc! { "ping": 1 }, None)?; + client.database("admin").run_command(doc! { "ping": 1 }).run()?; println!("Pinged your deployment. You successfully connected to MongoDB!"); Ok(()) diff --git a/source/includes/fundamentals/code-snippets/crud/change.rs b/source/includes/fundamentals/code-snippets/crud/change.rs index 7f53b287..66b56883 100644 --- a/source/includes/fundamentals/code-snippets/crud/change.rs +++ b/source/includes/fundamentals/code-snippets/crud/change.rs @@ -23,7 +23,7 @@ async fn main() -> mongodb::error::Result<()> { }; let res = my_coll - .update_many(doc! { "department": "Marketing" }, update_doc, None) + .update_many(doc! { "department": "Marketing" }, update_doc) .await?; println!("Modified documents: {}", res.modified_count); // end-update @@ -37,7 +37,7 @@ async fn main() -> mongodb::error::Result<()> { }; let res = my_coll - .update_one(filter_doc, update_doc, None) + .update_one(filter_doc, update_doc) .await?; println!("Modified documents: {}", res.modified_count); // end-update-by-id @@ -50,7 +50,7 @@ async fn main() -> mongodb::error::Result<()> { }; let res = my_coll - .replace_one(doc! { "name": "Matt DeGuy" }, replace_doc, None) + .replace_one(doc! { "name": "Matt DeGuy" }, replace_doc) .await?; println!( "Matched documents: {}\nModified documents: {}", @@ -61,8 +61,10 @@ async fn main() -> mongodb::error::Result<()> { let filter_doc = doc! {}; // begin-options - let opts: UpdateOptions = UpdateOptions::builder().upsert(true).build(); - let res = my_coll.update_one(filter_doc, update_doc, opts).await?; + let res = my_coll + .update_one(filter_doc, update_doc) + .upsert(true) + .await?; // end-options Ok(()) diff --git a/source/includes/fundamentals/code-snippets/crud/compound.rs b/source/includes/fundamentals/code-snippets/crud/compound.rs index aabc85a8..39b781a1 100644 --- a/source/includes/fundamentals/code-snippets/crud/compound.rs +++ b/source/includes/fundamentals/code-snippets/crud/compound.rs @@ -1,6 +1,5 @@ -use bson::{ Document, bson }; use mongodb::{ - bson::doc, + bson::{ Document, bson, doc }, options::{ FindOneAndDeleteOptions, FindOneAndUpdateOptions, @@ -20,22 +19,24 @@ async fn main() -> mongodb::error::Result<()> { let filter = doc! { "name": "xxx" }; // begin-find-delete-options - let opts = FindOneAndDeleteOptions::builder().comment(bson!("hello")).build(); - let res = my_coll.find_one_and_delete(filter, opts).await?; + let res = my_coll.find_one_and_delete(filter) + .comment(bson!("hello")) + .await?; // end-find-delete-options // begin-find_one_and_delete let filter = doc! { "age": doc! { "$lte": 10 } }; - let res = my_coll.find_one_and_delete(filter, None).await?; + let res = my_coll.find_one_and_delete(filter).await?; println!("Deleted document:\n{:?}", res); // end-find_one_and_delete let filter = doc! { "name": "xxx" }; let update = doc! { "$set": doc! { "check": true } }; // begin-find-update-options - let opts = FindOneAndUpdateOptions::builder().comment(bson!("hello")).build(); - let res = my_coll.find_one_and_update(filter, update, opts).await?; + let res = my_coll.find_one_and_update(filter, update) + .comment(bson!("hello")) + .await?; // end-find-update-options // begin-find_one_and_update @@ -43,19 +44,19 @@ async fn main() -> mongodb::error::Result<()> { let update = doc! { "$set": doc! { "school": "Durango High School" }, "$inc": doc! { "age": 1 } }; - let opts = FindOneAndUpdateOptions::builder() - .return_document(Some(ReturnDocument::After)) - .build(); - let res = my_coll.find_one_and_update(filter, update, opts).await?; + let res = my_coll.find_one_and_update(filter, update) + .return_document(ReturnDocument::After) + .await?; println!("Updated document:\n{:?}", res); // end-find_one_and_update let filter = doc! { "name": "xxx" }; let replacement = doc! { "name": "yyy", "age": 10 }; // begin-find-replace-options - let opts = FindOneAndReplaceOptions::builder().comment(bson!("hello")).build(); - let res = my_coll.find_one_and_replace(filter, replacement, opts).await?; + let res = my_coll.find_one_and_replace(filter, replacement) + .comment(bson!("hello")) + .await?; // end-find-replace-options // begin-find_one_and_replace @@ -64,12 +65,11 @@ async fn main() -> mongodb::error::Result<()> { doc! { "name": "Toby Fletcher", "age": 14, "school": "Durango High School" }; - let opts = FindOneAndReplaceOptions::builder() - .return_document(Some(ReturnDocument::After)) - .projection(doc! { "name": 1, "school": 1, "_id": 0 }) - .build(); - let res = my_coll.find_one_and_replace(filter, replacement, opts).await?; + let res = my_coll.find_one_and_replace(filter, replacement) + .return_document(ReturnDocument::After) + .projection(doc! { "name": 1, "school": 1, "_id": 0 }) + .await?; println!("Document after replacement:\n{:?}", res); // end-find_one_and_replace diff --git a/source/includes/fundamentals/code-snippets/crud/cursor.rs b/source/includes/fundamentals/code-snippets/crud/cursor.rs index ab77898d..ebcf42e5 100644 --- a/source/includes/fundamentals/code-snippets/crud/cursor.rs +++ b/source/includes/fundamentals/code-snippets/crud/cursor.rs @@ -40,10 +40,10 @@ async fn main() -> mongodb::error::Result<()> { //end-sample-data // Inserts sample documents into the collection - let insert_many_result = my_coll.insert_many(docs, None).await?; + let insert_many_result = my_coll.insert_many(docs).await?; // start-indiv-builtin - let mut cursor = my_coll.find(doc! { "color": "red" }, None).await?; + let mut cursor = my_coll.find(doc! { "color": "red" }).await?; while cursor.advance().await? { println!("{:?}", cursor.deserialize_current()?); } @@ -52,14 +52,14 @@ async fn main() -> mongodb::error::Result<()> { println!(); // start-indiv-stream - let mut cursor = my_coll.find(doc! { "color": "red" }, None).await?; + let mut cursor = my_coll.find(doc! { "color": "red" }).await?; println!("Output from next() iteration:"); while let Some(doc) = cursor.next().await { println!("{:?}", doc?); } println!(); - let mut cursor = my_coll.find(doc! { "color": "yellow" }, None).await?; + let mut cursor = my_coll.find(doc! { "color": "yellow" }).await?; println!("Output from try_next() iteration:"); while let Some(doc) = cursor.try_next().await? { println!("{:?}", doc); @@ -69,24 +69,24 @@ async fn main() -> mongodb::error::Result<()> { println!(); // start-array - let cursor = my_coll.find(doc! { "color": "red" }, None).await?; + let cursor = my_coll.find(doc! { "color": "red" }).await?; println!("Output from collect():"); let v: Vec> = cursor.collect().await; println!("{:?}", v); println!(); - let cursor = my_coll.find(doc! { "color": "yellow" }, None).await?; + let cursor = my_coll.find(doc! { "color": "yellow" }).await?; println!("Output from try_collect():"); let v: Vec = cursor.try_collect().await?; println!("{:?}", v); // end-array // start-options - let opts: FindOptions = FindOptions::builder() + let mut cursor = my_coll.find(doc! { "color": "red" }) .batch_size(5) .cursor_type(CursorType::Tailable) .no_cursor_timeout(true) - .build(); + .await?; // end-options Ok(()) diff --git a/source/includes/fundamentals/code-snippets/crud/delete.rs b/source/includes/fundamentals/code-snippets/crud/delete.rs index 26d8b19d..e790f2a5 100644 --- a/source/includes/fundamentals/code-snippets/crud/delete.rs +++ b/source/includes/fundamentals/code-snippets/crud/delete.rs @@ -12,15 +12,19 @@ async fn main() -> mongodb::error::Result<()> { // begin-delete let filter = doc! { "category": "garden" }; let hint = Hint::Name("_id_".to_string()); - let opts: DeleteOptions = DeleteOptions::builder().hint(hint).build(); - let res = my_coll.delete_many(filter, opts).await?; + let res = my_coll + .delete_many(filter) + .hint(hint) + .await?; println!("Deleted documents: {}", res.deleted_count); // end-delete // begin-options - let opts: DeleteOptions = DeleteOptions::builder().comment(bson!("hello!")).build(); - let res = my_coll.delete_one(filter, opts).await?; + let res = my_coll + .delete_one(filter) + .comment(bson!("hello!")) + .await?; // end-options Ok(()) diff --git a/source/includes/fundamentals/code-snippets/crud/geo.rs b/source/includes/fundamentals/code-snippets/crud/geo.rs index 08c0cd13..ab366967 100644 --- a/source/includes/fundamentals/code-snippets/crud/geo.rs +++ b/source/includes/fundamentals/code-snippets/crud/geo.rs @@ -56,7 +56,7 @@ async fn main() -> mongodb::error::Result<()> { .keys(doc! { "location.geo": "2dsphere" }) .build(); - let idx = my_coll.create_index(index, None).await?; + let idx = my_coll.create_index(index).await?; println!("Created index:\n{}", idx.index_name); // end-2dsphere @@ -65,7 +65,7 @@ async fn main() -> mongodb::error::Result<()> { .keys(doc! { "location.geo.coordinates": "2d" }) .build(); - let idx = my_coll.create_index(index, None).await?; + let idx = my_coll.create_index(index).await?; println!("Created index:\n{}", idx.index_name); // end-2d @@ -81,7 +81,7 @@ async fn main() -> mongodb::error::Result<()> { } }; - let mut cursor = my_coll.find(query, None).await?; + let mut cursor = my_coll.find(query).await?; while let Some(doc) = cursor.try_next().await? { println!("{}", doc); } @@ -105,7 +105,7 @@ async fn main() -> mongodb::error::Result<()> { doc! { "$geoWithin": { "$geometry": chicago }} }; - let mut cursor = my_coll.find(query, None).await?; + let mut cursor = my_coll.find(query).await?; while let Some(doc) = cursor.try_next().await? { println!("{}", doc); } diff --git a/source/includes/fundamentals/code-snippets/crud/insert.rs b/source/includes/fundamentals/code-snippets/crud/insert.rs index 9a078246..dd957cba 100644 --- a/source/includes/fundamentals/code-snippets/crud/insert.rs +++ b/source/includes/fundamentals/code-snippets/crud/insert.rs @@ -27,14 +27,14 @@ async fn main() -> mongodb::error::Result<()> { let my_coll: Collection = client.database("db").collection("books"); let doc = Book { _id: 8, title: "Atonement".to_string(), author: "Ian McEwan".to_string() }; - let insert_one_result = my_coll.insert_one(doc, None).await?; + let insert_one_result = my_coll.insert_one(doc).await?; println!("Inserted document with _id: {}", insert_one_result.inserted_id); // end-insert-one // begin-one-options - let _opts = InsertOneOptions::builder() + let _result = my_coll.insert_one(doc) .bypass_document_validation(true) - .build(); + .await?; // end-one-options // begin-insert-many @@ -56,7 +56,7 @@ async fn main() -> mongodb::error::Result<()> { } ]; - let insert_many_result = my_coll.insert_many(docs, None).await?; + let insert_many_result = my_coll.insert_many(docs).await?; println!("Inserted documents with _ids:"); for (_key, value) in &insert_many_result.inserted_ids { println!("{:?}", value); @@ -64,9 +64,9 @@ async fn main() -> mongodb::error::Result<()> { // end-insert-many // begin-many-options - let _opts = InsertManyOptions::builder() + let _result = my_coll.insert_many(docs) .comment(Some("hello world".into())) - .build(); + .await?; // end-many-options // begin-unordered @@ -76,9 +76,8 @@ async fn main() -> mongodb::error::Result<()> { Book { _id: 4, title: "Blueberries for Sal".to_string(), author: "".to_string() }, Book { _id: 3, title: "Goodnight Moon".to_string(), author: "".to_string() } ]; - - let opts = InsertManyOptions::builder().ordered(false).build(); - my_coll.insert_many(docs, opts).await?; + + my_coll.insert_many(docs).ordered(false).await?; // end-unordered Ok(()) diff --git a/source/includes/fundamentals/code-snippets/crud/query.rs b/source/includes/fundamentals/code-snippets/crud/query.rs index 1a15cee6..5dfed84a 100644 --- a/source/includes/fundamentals/code-snippets/crud/query.rs +++ b/source/includes/fundamentals/code-snippets/crud/query.rs @@ -57,11 +57,11 @@ async fn main() -> mongodb::error::Result<()> { //end-sample-docs // Inserts sample documents into the collection - let insert_many_result = my_coll.insert_many(docs, None).await?; + let insert_many_result = my_coll.insert_many(docs).await?; //begin-literal let query = doc! { "name": "pear" }; - let mut cursor = my_coll.find(query, None).await?; + let mut cursor = my_coll.find(query).await?; while let Some(doc) = cursor.try_next().await? { println!("{:?}", doc); } @@ -70,7 +70,7 @@ async fn main() -> mongodb::error::Result<()> { //begin-comparison // $gt means "greater than" let query = doc! { "quantity": doc! { "$gt": 5 } }; - let mut cursor = my_coll.find(query, None).await?; + let mut cursor = my_coll.find(query).await?; while let Some(doc) = cursor.try_next().await? { println!("{:?}", doc); } @@ -83,7 +83,7 @@ async fn main() -> mongodb::error::Result<()> { doc! { "quantity": doc! { "$mod": [ 3, 0 ] } } ] }; - let mut cursor = my_coll.find(query, None).await?; + let mut cursor = my_coll.find(query).await?; while let Some(doc) = cursor.try_next().await? { println!("{:?}", doc); } @@ -91,7 +91,7 @@ async fn main() -> mongodb::error::Result<()> { println!(""); //begin-element let query = doc! { "description": doc! { "$exists": true } }; - let mut cursor = my_coll.find(query, None).await?; + let mut cursor = my_coll.find(query).await?; while let Some(doc) = cursor.try_next().await? { println!("{:?}", doc); } @@ -100,7 +100,7 @@ async fn main() -> mongodb::error::Result<()> { //begin-evaluation // $mod means "modulo" and checks if the remainder is a specific value let query = doc! { "quantity": doc! { "$mod": [ 3, 0 ] } }; - let mut cursor = my_coll.find(query, None).await?; + let mut cursor = my_coll.find(query).await?; while let Some(doc) = cursor.try_next().await? { println!("{:?}", doc); } @@ -108,7 +108,7 @@ async fn main() -> mongodb::error::Result<()> { println!(""); //begin-bitwise let query = doc! { "quantity": doc! { "$bitsAllSet": 7 } }; - let mut cursor = my_coll.find(query, None).await?; + let mut cursor = my_coll.find(query).await?; while let Some(doc) = cursor.try_next().await? { println!("{:?}", doc); } @@ -116,7 +116,7 @@ async fn main() -> mongodb::error::Result<()> { println!(""); //begin-array let query = doc! { "vendors": doc! { "$elemMatch": { "$eq": "C" } } }; - let mut cursor = my_coll.find(query, None).await?; + let mut cursor = my_coll.find(query).await?; while let Some(doc) = cursor.try_next().await? { println!("{:?}", doc); } diff --git a/source/includes/fundamentals/code-snippets/crud/retrieve.rs b/source/includes/fundamentals/code-snippets/crud/retrieve.rs index 0e64df8c..13101d3e 100644 --- a/source/includes/fundamentals/code-snippets/crud/retrieve.rs +++ b/source/includes/fundamentals/code-snippets/crud/retrieve.rs @@ -18,7 +18,7 @@ async fn main() -> mongodb::error::Result<()> { let my_coll: Collection = client.database("db").collection("inventory"); // start-sample - let docs = vec! [ + let docs = vec![ Inventory { item: "candle".to_string(), category: "decor".to_string(), @@ -38,41 +38,35 @@ async fn main() -> mongodb::error::Result<()> { item: "watering can".to_string(), category: "garden".to_string(), unit_price: 11.99, - } + }, ]; // end-sample // Inserts sample documents into the collection - let insert_many_result = my_coll.insert_many(docs, None).await?; + let insert_many_result = my_coll.insert_many(docs).await?; // begin-find-many - let opts = FindOptions::builder() + let mut cursor = my_coll + .find(doc! { "$and": vec! + [ + doc! { "unit_price": doc! { "$lt": 12.00 } }, + doc! { "category": doc! { "$ne": "kitchen" } } + ] }) .sort(doc! { "unit_price": -1 }) - .build(); - - let mut cursor = my_coll.find( - doc! { "$and": vec! - [ - doc! { "unit_price": doc! { "$lt": 12.00 } }, - doc! { "category": doc! { "$ne": "kitchen" } } - ] }, - opts - ).await?; + .await?; while let Some(result) = cursor.try_next().await? { println!("{:?}", result); - }; - + } + // end-find-many print!("\n"); // begin-find-one - let opts = FindOneOptions::builder().skip(2).build(); - let result = my_coll.find_one( - doc! { "unit_price": - doc! { "$lte": 20.00 } }, - opts - ).await?; + let result = my_coll + .find_one(doc! { "unit_price": doc! { "$lte": 20.00 } }) + .skip(2) + .await?; println!("{:#?}", result); // end-find-one @@ -81,14 +75,14 @@ async fn main() -> mongodb::error::Result<()> { // begin-agg let pipeline = vec![ doc! { "$group": doc! { "_id" : doc! {"category": "$category"} , - "avg_price" : doc! { "$avg" : "$unit_price" } } }, - doc! { "$sort": { "_id.avg_price" : 1 } } + "avg_price" : doc! { "$avg" : "$unit_price" } } }, + doc! { "$sort": { "_id.avg_price" : 1 } }, ]; - let mut cursor = my_coll.aggregate(pipeline, None).await?; + let mut cursor = my_coll.aggregate(pipeline).await?; while let Some(result) = cursor.try_next().await? { println!("{:?}", result); - }; + } // end-agg Ok(()) diff --git a/source/includes/fundamentals/code-snippets/crud/text.rs b/source/includes/fundamentals/code-snippets/crud/text.rs index b0fe14e6..a74dae38 100644 --- a/source/includes/fundamentals/code-snippets/crud/text.rs +++ b/source/includes/fundamentals/code-snippets/crud/text.rs @@ -39,8 +39,7 @@ async fn main() -> mongodb::error::Result<()> { name: "Garlic Butter Trout".to_string(), description: "Baked trout seasoned with garlic, lemon, dill, and, of course, butter. Serves 2.".to_string(), }, - ], - None + ] ).await?; // begin-idx @@ -48,13 +47,13 @@ async fn main() -> mongodb::error::Result<()> { .keys(doc! { "description": "text" }) .build(); - let idx_res = my_coll.create_index(index, None).await?; + let idx_res = my_coll.create_index(index).await?; // end-idx // begin-by-term let filter = doc! { "$text": { "$search": "herb" } }; - let mut cursor = my_coll.find(filter, None).await?; + let mut cursor = my_coll.find(filter).await?; while let Some(doc) = cursor.try_next().await? { println!("{:?}", doc); } @@ -63,7 +62,7 @@ async fn main() -> mongodb::error::Result<()> { // begin-by-phrase let filter = doc! { "$text": { "$search": "\"serves 2\"" } }; - let mut cursor = my_coll.find(filter, None).await?; + let mut cursor = my_coll.find(filter).await?; while let Some(doc) = cursor.try_next().await? { println!("{:?}", doc); } @@ -72,7 +71,7 @@ async fn main() -> mongodb::error::Result<()> { // begin-exclude-term let filter = doc! { "$text": { "$search": "vegan -tofu" } }; - let mut cursor = my_coll.find(filter, None).await?; + let mut cursor = my_coll.find(filter).await?; while let Some(doc) = cursor.try_next().await? { println!("{:?}", doc); } @@ -88,10 +87,12 @@ async fn main() -> mongodb::error::Result<()> { "name": 1, "score": { "$meta": "textScore" } }; - let opts = FindOptions::builder().sort(sort).projection(projection).build(); let doc_coll: Collection = my_coll.clone_with_type(); - let mut cursor = doc_coll.find(filter, opts).await?; + let mut cursor = doc_coll.find(filter) + .sort(sort) + .projection(projection) + .await?; while let Some(doc) = cursor.try_next().await? { println!("{:?}", doc); @@ -101,7 +102,7 @@ async fn main() -> mongodb::error::Result<()> { // begin-agg-term let match_stage = doc! { "$match": { "$text": { "$search": "herb" } } }; - let mut cursor = my_coll.aggregate([match_stage], None).await?; + let mut cursor = my_coll.aggregate([match_stage]).await?; while let Some(doc) = cursor.try_next().await? { println!("{:?}", doc); } @@ -118,7 +119,7 @@ async fn main() -> mongodb::error::Result<()> { } }; let pipeline = [match_stage, sort_stage, proj_stage]; - let mut cursor = my_coll.aggregate(pipeline, None).await?; + let mut cursor = my_coll.aggregate(pipeline).await?; while let Some(doc) = cursor.try_next().await? { println!("{:?}", doc); } diff --git a/source/includes/fundamentals/code-snippets/crud/watch.rs b/source/includes/fundamentals/code-snippets/crud/watch.rs index a48317f4..d639c3b5 100644 --- a/source/includes/fundamentals/code-snippets/crud/watch.rs +++ b/source/includes/fundamentals/code-snippets/crud/watch.rs @@ -37,10 +37,10 @@ async fn main() -> mongodb::error::Result<()> { ]; // end-docs - let insert_many_result = my_coll.insert_many(docs, None).await?; + let insert_many_result = my_coll.insert_many(docs).await?; // start-open - let mut change_stream = my_coll.watch(None, None).await?; + let mut change_stream = my_coll.watch().await?; while let Some(event) = change_stream.next().await.transpose()? { println!("Operation performed: {:?}", event.operation_type); @@ -49,11 +49,10 @@ async fn main() -> mongodb::error::Result<()> { // end-open // start-pipeline - let pipeline = vec![ - doc! { "$match" : doc! { "operationType" : "update" } } - ]; + let mut update_change_stream = my_coll.watch() + .pipeline(vec![doc! { "$match" : doc! { "operationType" : "update" } }]) + .await?; - let mut update_change_stream = my_coll.watch(pipeline, None).await?; while let Some(event) = update_change_stream.next().await.transpose()? { println!("Update performed: {:?}", event.update_description); } @@ -61,20 +60,19 @@ async fn main() -> mongodb::error::Result<()> { // start-create-coll let enable = ChangeStreamPreAndPostImages::builder().enabled(true).build(); - let opts = CreateCollectionOptions::builder() - .change_stream_pre_and_post_images(enable) - .build(); - let result = my_db.create_collection("directors", opts).await?; + let result = my_db.create_collection("directors") + .change_stream_pre_and_post_images(enable) + .await?; // end-create-coll // start-pre - let pre_image = Some(FullDocumentBeforeChangeType::Required); - let opts = ChangeStreamOptions::builder() + let pre_image = FullDocumentBeforeChangeType::Required; + + let mut change_stream = my_coll.watch() .full_document_before_change(pre_image) - .build(); + .await?; - let mut change_stream = my_coll.watch(None, opts).await?; while let Some(event) = change_stream.next().await.transpose()? { println!("Operation performed: {:?}", event.operation_type); println!("Pre-image: {:?}", event.full_document_before_change); @@ -82,12 +80,12 @@ async fn main() -> mongodb::error::Result<()> { // end-pre // start-post - let post_image = Some(FullDocumentType::WhenAvailable); - let opts = ChangeStreamOptions::builder() + let post_image = FullDocumentType::WhenAvailable; + + let mut change_stream = my_coll.watch() .full_document(post_image) - .build(); + .await?; - let mut change_stream = my_coll.watch(None, opts).await?; while let Some(event) = change_stream.next().await.transpose()? { println!("Operation performed: {:?}", event.operation_type); println!("Post-image: {:?}", event.full_document); diff --git a/source/includes/fundamentals/code-snippets/db-coll.rs b/source/includes/fundamentals/code-snippets/db-coll.rs index 48e76652..e5672e21 100644 --- a/source/includes/fundamentals/code-snippets/db-coll.rs +++ b/source/includes/fundamentals/code-snippets/db-coll.rs @@ -9,7 +9,7 @@ async fn main() -> mongodb::error::Result<()> { let client = Client::with_uri_str(uri).await?; // begin-list-db - let db_list = client.list_database_names(doc! {}, None).await?; + let db_list = client.list_database_names().await?; println!("{:?}", db_list); // end-list-db @@ -18,27 +18,28 @@ async fn main() -> mongodb::error::Result<()> { // end-database // begin-drop-db - db.drop(None).await?; + db.drop().await?; // end-drop-db let db = client.database("db"); // begin-list-coll - let coll_list = db.list_collection_names(doc! {}).await?; + let coll_list = db.list_collection_names().await?; println!("{:?}", coll_list); // end-list-coll // begin-coll let wc = WriteConcern::builder().journal(true).build(); + let coll_opts = CollectionOptions::builder().write_concern(wc).build(); let my_coll: Collection = db.collection_with_options("coll_xyz", coll_opts); // end-coll // begin-drop-coll - my_coll.drop(None).await?; + my_coll.drop().await?; // end-drop-coll // begin-create-coll - db.create_collection("coll_abc", None).await?; + db.create_collection("coll_abc").await?; // end-create-coll Ok(()) diff --git a/source/includes/fundamentals/code-snippets/gridfs.rs b/source/includes/fundamentals/code-snippets/gridfs.rs index 72baa2ba..d468bd68 100644 --- a/source/includes/fundamentals/code-snippets/gridfs.rs +++ b/source/includes/fundamentals/code-snippets/gridfs.rs @@ -38,7 +38,7 @@ async fn main() -> mongodb::error::Result<()> { let bucket = my_db.gridfs_bucket(None); let file_bytes = fs::read("example.txt").await?; - let mut upload_stream = bucket.open_upload_stream("example", None); + let mut upload_stream = bucket.open_upload_stream("example").await?; upload_stream.write_all(&file_bytes[..]).await?; println!("Document uploaded with ID: {}", upload_stream.id()); @@ -48,7 +48,7 @@ async fn main() -> mongodb::error::Result<()> { // start-retrieve let bucket = my_db.gridfs_bucket(None); let filter = doc! {}; - let mut cursor = bucket.find(filter, None).await?; + let mut cursor = bucket.find(filter).await?; while let Some(result) = cursor.try_next().await? { println!("File length: {}\n", result.length); @@ -71,7 +71,7 @@ async fn main() -> mongodb::error::Result<()> { let id = ObjectId::from_str("3289").expect("Could not convert to ObjectId"); let new_name = "new_file_name"; - bucket.rename(Bson::ObjectId(id), &new_name).await?; + bucket.rename(Bson::ObjectId(id), new_name).await?; // end-rename // start-delete-file diff --git a/source/includes/fundamentals/code-snippets/indexes.rs b/source/includes/fundamentals/code-snippets/indexes.rs index 249eb93b..1c7f3799 100644 --- a/source/includes/fundamentals/code-snippets/indexes.rs +++ b/source/includes/fundamentals/code-snippets/indexes.rs @@ -15,7 +15,7 @@ async fn main() -> mongodb::error::Result<()> { // begin-single-field let index = IndexModel::builder().keys(doc! { "city": 1 }).build(); - let idx = my_coll.create_index(index, None).await?; + let idx = my_coll.create_index(index).await?; println!("Created index:\n{}", idx.index_name); // end-single-field @@ -25,7 +25,7 @@ async fn main() -> mongodb::error::Result<()> { .keys(doc! { "city": 1, "pop": -1 }) .build(); - let idx = my_coll.create_index(index, None).await?; + let idx = my_coll.create_index(index).await?; println!("Created index:\n{}", idx.index_name); // end-compound @@ -33,18 +33,16 @@ async fn main() -> mongodb::error::Result<()> { // begin-multikey let index = IndexModel::builder().keys(doc! { "tags": 1 }).build(); - let idx = my_coll.create_index(index, None).await?; + let idx = my_coll.create_index(index).await?; println!("Created index:\n{}", idx.index_name); // end-multikey - // begin-clustered let db = client.database("sample_training"); let cl_idx = ClusteredIndex::default(); - let opts = CreateCollectionOptions::builder() - .clustered_index(cl_idx) - .build(); - db.create_collection("items", opts).await?; + db.create_collection("items") + .clustered_index(cl_idx) + .await?; // end-clustered let my_coll: Collection = client.database("sample_training").collection("posts"); @@ -58,7 +56,7 @@ async fn main() -> mongodb::error::Result<()> { .options(idx_opts) .build(); - let idx = my_coll.create_index(index, None).await?; + let idx = my_coll.create_index(index).await?; println!("Created index:\n{}", idx.index_name); // end-text @@ -85,7 +83,7 @@ async fn main() -> mongodb::error::Result<()> { .name("example_index".to_string()) .build(); - let result = my_coll.create_search_index(idx_model, None).await?; + let result = my_coll.create_search_index(idx_model).await?; println!("Created Atlas Search index:\n{}", result); // end-atlas-create-one @@ -102,12 +100,12 @@ async fn main() -> mongodb::error::Result<()> { .build(); let models = vec![dyn_idx, static_idx]; - let result = my_coll.create_search_indexes(models, None).await?; + let result = my_coll.create_search_indexes(models).await?; println!("Created Atlas Search indexes:\n{:?}", result); // end-atlas-create-many // begin-atlas-list - let mut cursor = my_coll.list_search_indexes(None, None, None).await?; + let mut cursor = my_coll.list_search_indexes().await?; while let Some(index) = cursor.try_next().await? { println!("{}\n", index); } @@ -116,12 +114,12 @@ async fn main() -> mongodb::error::Result<()> { // begin-atlas-update let name = "static_index"; let definition = doc! { "mappings": doc! {"dynamic": true} }; - my_coll.update_search_index(name, definition, None).await?; + my_coll.update_search_index(name, definition).await?; // end-atlas-update // begin-atlas-drop let name = "example_index"; - my_coll.drop_search_index(name, None).await?; + my_coll.drop_search_index(name).await?; // end-atlas-drop let my_coll: Collection = client.database("sample_mflix").collection("theaters"); @@ -130,7 +128,7 @@ async fn main() -> mongodb::error::Result<()> { .keys(doc! { "location.geo": "2dsphere" }) .build(); - let idx = my_coll.create_index(index, None).await?; + let idx = my_coll.create_index(index).await?; println!("Created index:\n{}", idx.index_name); // end-geo @@ -145,7 +143,7 @@ async fn main() -> mongodb::error::Result<()> { let my_coll: Collection = client.database("sample_training").collection("zips"); // begin-drop - my_coll.drop_index("city_1".to_string(), None).await?; + my_coll.drop_index("city_1".to_string()).await?; // end-drop Ok(()) diff --git a/source/includes/fundamentals/code-snippets/logging.rs b/source/includes/fundamentals/code-snippets/logging.rs index dbb5b2cc..5bce560a 100644 --- a/source/includes/fundamentals/code-snippets/logging.rs +++ b/source/includes/fundamentals/code-snippets/logging.rs @@ -12,7 +12,7 @@ async fn main() -> Result<()> { // start-operation let my_coll = client.database("db").collection("test_coll"); - my_coll.insert_one(doc! { "x" : 1 }, None).await?; + my_coll.insert_one(doc! { "x" : 1 }).await?; // end-operation Ok(()) diff --git a/source/includes/fundamentals/code-snippets/network-compression.rs b/source/includes/fundamentals/code-snippets/network-compression.rs index ccfab0d0..77e927dc 100644 --- a/source/includes/fundamentals/code-snippets/network-compression.rs +++ b/source/includes/fundamentals/code-snippets/network-compression.rs @@ -21,7 +21,7 @@ async fn main() -> mongodb::error::Result<()> { let client = Client::with_options(client_options)?; // end-clientoptions - client.database("admin").run_command(doc! { "ping": 1 }, None).await?; + client.database("admin").run_command(doc! { "ping": 1 }).await?; println!("Pinged your deployment. You successfully connected to MongoDB!"); Ok(()) diff --git a/source/includes/fundamentals/code-snippets/performance-bundle-runtime.rs b/source/includes/fundamentals/code-snippets/performance-bundle-runtime.rs index 46c16d57..a842ab7f 100644 --- a/source/includes/fundamentals/code-snippets/performance-bundle-runtime.rs +++ b/source/includes/fundamentals/code-snippets/performance-bundle-runtime.rs @@ -13,7 +13,7 @@ static CLIENT_RUNTIME: Lazy<(Client, Runtime)> = Lazy::new(|| { fn test_list_dbs() -> Result<(), Box> { let (client, rt) = &*CLIENT_RUNTIME; rt.block_on(async { - client.list_database_names(None, None).await + client.list_database_names().await })?; Ok(()) } diff --git a/source/includes/fundamentals/code-snippets/performance-new-client.rs b/source/includes/fundamentals/code-snippets/performance-new-client.rs index 6da9a5b1..34153728 100644 --- a/source/includes/fundamentals/code-snippets/performance-new-client.rs +++ b/source/includes/fundamentals/code-snippets/performance-new-client.rs @@ -1,6 +1,6 @@ #[tokio::test] async fn test_list_dbs() -> Result<(), Box> { let client = Client::with_uri_str("").await?; - client.list_database_names(None, None).await?; + client.list_database_names().await?; Ok(()) } diff --git a/source/includes/fundamentals/code-snippets/performance-parallel.rs b/source/includes/fundamentals/code-snippets/performance-parallel.rs index cedc569b..34262e7f 100644 --- a/source/includes/fundamentals/code-snippets/performance-parallel.rs +++ b/source/includes/fundamentals/code-snippets/performance-parallel.rs @@ -10,6 +10,6 @@ for i in 0..5 { .database("items") .collection::(&format!("coll{}", i)); - collection.insert_one(data_ref, None).await + collection.insert_one(data_ref).await }); } diff --git a/source/includes/fundamentals/code-snippets/quick-reference-async.rs b/source/includes/fundamentals/code-snippets/quick-reference-async.rs index 536178fb..fb40f14f 100644 --- a/source/includes/fundamentals/code-snippets/quick-reference-async.rs +++ b/source/includes/fundamentals/code-snippets/quick-reference-async.rs @@ -1,13 +1,7 @@ -use std::env; use bson::Document; -use mongodb::{ - bson::doc, - Client, - Collection, - options::FindOptions, - IndexModel -}; use futures::TryStreamExt; +use mongodb::{bson::doc, options::FindOptions, Client, Collection, IndexModel}; +use std::env; #[tokio::main] async fn main() -> mongodb::error::Result<()> { @@ -18,24 +12,21 @@ async fn main() -> mongodb::error::Result<()> { let collection: Collection = client.database("sample_mflix").collection("movies"); // start-find-one - let result = collection.find_one( - doc! { "title": "Peter Pan" }, - None - ).await?; + let result = collection.find_one(doc! { "title": "Peter Pan" }).await?; //end-find-one // start-find-multiple let filter = doc! { "year": 1925 }; - let mut cursor = collection.find(filter, None).await?; + let mut cursor = collection.find(filter).await?; // end-find-multiple // start-insert-one - let doc = doc! { - "title": "Mistress America", "type": "movie" + let doc = doc! { + "title": "Mistress America", "type": "movie" }; - let result = collection.insert_one(doc, None).await?; - // end-insert-one + let result = collection.insert_one(doc).await?; + // end-insert-one // start-insert-many let docs = vec![ @@ -44,79 +35,67 @@ async fn main() -> mongodb::error::Result<()> { doc! { "title": "You Hurt My Feelings", "runtime": 93 }, ]; - let result = collection.insert_many(docs, None).await?; + let result = collection.insert_many(docs).await?; // end-insert-many // start-update-one let filter = doc! { "title": "Burn After Reading"}; - let update = - doc! { + let update = doc! { "$set": doc!{ "num_mflix_comments": 1 } }; - let result = collection.update_one( - filter, update, None - ).await?; + let result = collection.update_one(filter, update).await?; // end-update-one - + // start-update-many let filter = doc! { "rated": "PASSED"}; - let update = - doc! { + let update = doc! { "$set": doc!{ "rated": "Not Rated" } }; - let result = collection.update_many( - filter, update, None - ).await?; + let result = collection.update_many(filter, update).await?; // end-update-many // start-replace let filter = doc! { "title": "è Nous la Libertè" }; - let replacement = - doc! { + let replacement = doc! { "title": "À nous la liberté", "type": "movie", "directors": vec! [ "René Clair" ] }; - let result = collection.replace_one( - filter, replacement, None - ).await?; + let result = collection.replace_one(filter, replacement).await?; // end-replace // start-delete-one let filter = doc! { "title": "Search and Destroy" }; - let result = collection.delete_one(filter, None).await?; + let result = collection.delete_one(filter).await?; // end-delete-one // start-delete-many - let filter = doc! { - "year": doc! { "$lt": 1920 } + let filter = doc! { + "year": doc! { "$lt": 1920 } }; - let result = collection.delete_many(filter, None).await?; + let result = collection.delete_many(filter).await?; // end-delete-many // start-cursor-iterative - let mut cursor = collection.find( - doc! { "$and": vec! - [ - doc! { "metacritic": doc! { "$gt": 90 } }, - doc! { "directors": vec! [ "Martin Scorsese" ] } - ] }, - None - ).await?; + let mut cursor = collection + .find(doc! { "$and": vec! + [ + doc! { "metacritic": doc! { "$gt": 90 } }, + doc! { "directors": vec! [ "Martin Scorsese" ] } + ] }) + .await?; while let Some(result) = cursor.try_next().await? { println!("{}", result); - }; + } // end-cursor-iterative // start-cursor-array - let cursor = collection.find( - doc! { "title": "Secrets & Lies" }, None - ).await?; + let cursor = collection.find(doc! { "title": "Secrets & Lies" }).await?; let results: Vec = cursor.try_collect().await?; // end-cursor-array @@ -126,7 +105,7 @@ async fn main() -> mongodb::error::Result<()> { "languages": vec! [ "Mandarin" ] }; - let result = collection.count_documents(filter, None).await?; + let result = collection.count_documents(filter).await?; // end-count // start-distinct @@ -135,57 +114,43 @@ async fn main() -> mongodb::error::Result<()> { "directors": vec! [ "Sean Baker" ] }; - let results = collection.distinct( - field_name, filter, None - ).await?; + let results = collection.distinct(field_name, filter).await?; // end-distinct // start-limit - let opts: FindOptions = FindOptions::builder() - .limit(5) - .build(); - let filter = doc! { "awards.wins": 25}; - let mut cursor = collection.find(filter, opts).await?; + let mut cursor = collection.find(filter).limit(5).await?; // end-limit // start-skip - let opts: FindOptions = FindOptions::builder() - .skip(1) - .build(); - let filter = doc! { "runtime": 100 }; - let mut cursor = collection.find(filter, opts).await?; + let mut cursor = collection.find(filter).skip(1).await?; // end-skip // start-sort - let opts: FindOptions = FindOptions::builder() - .sort(doc! { "imdb.rating": 1 }) - .build(); - let filter = doc! { "directors": vec! [ "Nicole Holofcener" ] }; - let mut cursor = collection.find(filter, opts).await?; + let mut cursor = collection + .find(filter) + .sort(doc! { "imdb.rating": 1 }) + .await?; // end-sort // start-project - let opts: FindOptions = FindOptions::builder() - .projection(doc! { "title": 1, "metacritic": 1, "_id": 0 }) - .build(); - let filter = doc! { "year": 2015 }; - let mut cursor = collection.find(filter, opts).await?; + let mut cursor = collection + .find(filter) + .projection(doc! { "title": 1, "metacritic": 1, "_id": 0 }) + .await?; // end-project // start-index - let index: IndexModel = IndexModel::builder() - .keys(doc! { "title": 1 }) - .build(); + let index: IndexModel = IndexModel::builder().keys(doc! { "title": 1 }).build(); - let result = collection.create_index(index, None).await?; + let result = collection.create_index(index).await?; // end-index Ok(()) -} \ No newline at end of file +} diff --git a/source/includes/fundamentals/code-snippets/quick-reference-sync.rs b/source/includes/fundamentals/code-snippets/quick-reference-sync.rs index 958b83ff..2e2ca7b8 100644 --- a/source/includes/fundamentals/code-snippets/quick-reference-sync.rs +++ b/source/includes/fundamentals/code-snippets/quick-reference-sync.rs @@ -1,11 +1,11 @@ -use std::env; use mongodb::{ bson::{doc, Document}, error::Result, - sync::{Client, Collection}, options::FindOptions, - IndexModel + sync::{Client, Collection}, + IndexModel, }; +use std::env; fn main() -> Result<()> { let uri = ""; @@ -15,24 +15,21 @@ fn main() -> Result<()> { let collection: Collection = client.database("sample_mflix").collection("movies"); // start-find-one - let result = collection.find_one( - doc! { "title": "Peter Pan" }, - None - )?; + let result = collection.find_one(doc! { "title": "Peter Pan" }).run()?; //end-find-one // start-find-multiple let filter = doc! { "year": 1925 }; - let mut cursor = collection.find(filter, None)?; + let mut cursor = collection.find(filter).run()?; // end-find-multiple // start-insert-one - let doc = doc! { - "title": "Mistress America", "type": "movie" + let doc = doc! { + "title": "Mistress America", "type": "movie" }; - let result = collection.insert_one(doc, None)?; - // end-insert-one + let result = collection.insert_one(doc).run()?; + // end-insert-one // start-insert-many let docs = vec![ @@ -41,79 +38,67 @@ fn main() -> Result<()> { doc! { "title": "You Hurt My Feelings", "runtime": 93 }, ]; - let result = collection.insert_many(docs, None)?; + let result = collection.insert_many(docs).run()?; // end-insert-many // start-update-one let filter = doc! { "title": "Burn After Reading"}; - let update = - doc! { + let update = doc! { "$set": doc!{ "num_mflix_comments": 1 } }; - let result = collection.update_one( - filter, update, None - )?; + let result = collection.update_one(filter, update).run()?; // end-update-one - + // start-update-many let filter = doc! { "rated": "PASSED"}; - let update = - doc! { + let update = doc! { "$set": doc!{ "rated": "Not Rated" } }; - let result = collection.update_many( - filter, update, None - )?; + let result = collection.update_many(filter, update).run()?; // end-update-many // start-replace let filter = doc! { "title": "è Nous la Libertè" }; - let replacement = - doc! { + let replacement = doc! { "title": "À nous la liberté", "type": "movie", "directors": vec! [ "René Clair" ] }; - let result = collection.replace_one( - filter, replacement, None - )?; + let result = collection.replace_one(filter, replacement).run()?; // end-replace // start-delete-one let filter = doc! { "title": "Search and Destroy" }; - let result = collection.delete_one(filter, None)?; + let result = collection.delete_one(filter).run()?; // end-delete-one // start-delete-many - let filter = doc! { - "year": doc! { "$lt": 1920 } + let filter = doc! { + "year": doc! { "$lt": 1920 } }; - let result = collection.delete_many(filter, None)?; + let result = collection.delete_many(filter).run()?; // end-delete-many // start-cursor-iterative - let cursor = collection.find( - doc! { "$and": vec! - [ - doc! { "metacritic": doc! { "$gt": 90 } }, - doc! { "directors": vec! [ "Martin Scorsese" ] } - ] }, - None - )?; + let cursor = collection + .find(doc! { "$and": vec! + [ + doc! { "metacritic": doc! { "$gt": 90 } }, + doc! { "directors": vec! [ "Martin Scorsese" ] } + ] }) + .run()?; for result in cursor { - println!("{}", result?); + println!("{}", result?); } // end-cursor-iterative // start-cursor-array - let cursor = collection.find( - doc! { "title": "Secrets & Lies" }, None - )?; + let cursor = collection.find(doc! { "title": "Secrets & Lies" }).run()?; let results: Vec> = cursor.collect(); // end-cursor-array @@ -123,7 +108,7 @@ fn main() -> Result<()> { "languages": vec! [ "Mandarin" ] }; - let result = collection.count_documents(filter, None)?; + let result = collection.count_documents(filter).run()?; // end-count // start-distinct @@ -132,56 +117,42 @@ fn main() -> Result<()> { "directors": vec! [ "Sean Baker" ] }; - let results = collection.distinct( - field_name, filter, None - )?; + let results = collection.distinct(field_name, filter).run()?; // end-distinct // start-limit - let opts: FindOptions = FindOptions::builder() - .limit(5) - .build(); - let filter = doc! { "awards.wins": 25}; - let mut cursor = collection.find(filter, opts)?; + let mut cursor = collection.find(filter).limit(5).run()?; // end-limit // start-skip - let opts: FindOptions = FindOptions::builder() - .skip(1) - .build(); - let filter = doc! { "runtime": 100 }; - let mut cursor = collection.find(filter, opts)?; + let mut cursor = collection.find(filter).skip(1).run()?; // end-skip // start-sort - let opts: FindOptions = FindOptions::builder() - .sort(doc! { "imdb.rating": 1 }) - .build(); - let filter = doc! { "directors": vec! [ "Nicole Holofcener" ] }; - let mut cursor = collection.find(filter, opts)?; + let mut cursor = collection + .find(filter) + .sort(doc! { "imdb.rating": 1 }) + .run()?; // end-sort // start-project - let opts: FindOptions = FindOptions::builder() - .projection(doc! { "title": 1, "metacritic": 1, "_id": 0 }) - .build(); - let filter = doc! { "year": 2015 }; - let mut cursor = collection.find(filter, opts)?; + let mut cursor = collection + .find(filter) + .projection(doc! { "title": 1, "metacritic": 1, "_id": 0 }) + .run()?; // end-project // start-index - let index: IndexModel = IndexModel::builder() - .keys(doc! { "title": 1 }) - .build(); + let index: IndexModel = IndexModel::builder().keys(doc! { "title": 1 }).build(); - let result = collection.create_index(index, None)?; + let result = collection.create_index(index).run()?; // end-index Ok(()) diff --git a/source/includes/fundamentals/code-snippets/run-command.rs b/source/includes/fundamentals/code-snippets/run-command.rs index e9bf0059..a7a59058 100644 --- a/source/includes/fundamentals/code-snippets/run-command.rs +++ b/source/includes/fundamentals/code-snippets/run-command.rs @@ -15,7 +15,7 @@ async fn main() -> mongodb::error::Result<()> { "verbosity": "queryPlanner" }; - let result = my_db.run_command(explain_command, None).await?; + let result = my_db.run_command(explain_command).await?; // end-runcommand println!("{}", result); diff --git a/source/includes/fundamentals/code-snippets/runtimes-sync.rs b/source/includes/fundamentals/code-snippets/runtimes-sync.rs index 16306a83..e9ce7429 100644 --- a/source/includes/fundamentals/code-snippets/runtimes-sync.rs +++ b/source/includes/fundamentals/code-snippets/runtimes-sync.rs @@ -12,6 +12,6 @@ fn main() { .database("items") .collection::(&format!("coll{}", i)); - collection.insert_one(somedata_ref, None); + collection.insert_one(somedata_ref); } } diff --git a/source/includes/fundamentals/code-snippets/runtimes-tokio.rs b/source/includes/fundamentals/code-snippets/runtimes-tokio.rs index aaf338c0..c73eec80 100644 --- a/source/includes/fundamentals/code-snippets/runtimes-tokio.rs +++ b/source/includes/fundamentals/code-snippets/runtimes-tokio.rs @@ -10,6 +10,6 @@ for i in 0..5 { .database("items") .collection::(&format!("coll{}", i)); - collection.insert_one(somedata_ref, None).await + collection.insert_one(somedata_ref).await }); } diff --git a/source/includes/fundamentals/code-snippets/schema-validation.rs b/source/includes/fundamentals/code-snippets/schema-validation.rs index b12a8931..05b7b202 100644 --- a/source/includes/fundamentals/code-snippets/schema-validation.rs +++ b/source/includes/fundamentals/code-snippets/schema-validation.rs @@ -1,5 +1,10 @@ use bson::{ Document }; -use mongodb::{ bson::doc, options::{ CollectionOptions, WriteConcern }, Client, Collection }; +use mongodb::{ + bson::doc, + options::{ CollectionOptions, WriteConcern, ValidationAction, ValidationLevel }, + Client, + Collection +}; use std::env; #[tokio::main] @@ -22,13 +27,12 @@ async fn main() -> mongodb::error::Result<()> { } } }; - let validation_opts = CreateCollectionOptions::builder() - .validator(validator) - .validation_action(Some(ValidationAction::Error)) - .validation_level(Some(ValidationLevel::Moderate)) - .build(); - db.create_collection("survey_answers", validation_opts).await?; + db.create_collection("survey_answers") + .validator(validator) + .validation_action(ValidationAction::Error) + .validation_level(ValidationLevel::Moderate) + .await?; // end-schema-validation Ok(()) diff --git a/source/includes/fundamentals/code-snippets/serialization.rs b/source/includes/fundamentals/code-snippets/serialization.rs index 50977ee6..df5a9077 100644 --- a/source/includes/fundamentals/code-snippets/serialization.rs +++ b/source/includes/fundamentals/code-snippets/serialization.rs @@ -39,7 +39,7 @@ async fn main() -> mongodb::error::Result<()> { tropical: true, }; - my_coll.insert_one(calabash, None).await?; + my_coll.insert_one(calabash).await?; // end-insert-veg // begin-multiple-types diff --git a/source/includes/fundamentals/code-snippets/stable-api-behavior.rs b/source/includes/fundamentals/code-snippets/stable-api-behavior.rs index db5f5525..20899ec7 100644 --- a/source/includes/fundamentals/code-snippets/stable-api-behavior.rs +++ b/source/includes/fundamentals/code-snippets/stable-api-behavior.rs @@ -21,7 +21,8 @@ fn main() -> mongodb::error::Result<()> { client .database("admin") - .run_command(doc! { "ping": 1 }, None)?; + .run_command(doc! { "ping": 1 }, None) + .run()?; println!("Pinged your deployment. You successfully connected to MongoDB!"); Ok(()) diff --git a/source/includes/fundamentals/code-snippets/stable-api.rs b/source/includes/fundamentals/code-snippets/stable-api.rs index 28d1fe64..65baa9f1 100644 --- a/source/includes/fundamentals/code-snippets/stable-api.rs +++ b/source/includes/fundamentals/code-snippets/stable-api.rs @@ -17,7 +17,8 @@ fn main() -> mongodb::error::Result<()> { client .database("admin") - .run_command(doc! { "ping": 1 }, None)?; + .run_command(doc! { "ping": 1 }, None) + .run()?; println!("Pinged your deployment. You successfully connected to MongoDB!"); Ok(()) diff --git a/source/includes/fundamentals/code-snippets/tracing.rs b/source/includes/fundamentals/code-snippets/tracing.rs index 60256f1b..9a7538a7 100644 --- a/source/includes/fundamentals/code-snippets/tracing.rs +++ b/source/includes/fundamentals/code-snippets/tracing.rs @@ -12,7 +12,7 @@ async fn main() -> Result<()> { // start-operation let my_coll = client.database("db").collection("test_coll"); - my_coll.insert_one(doc! { "x" : 1 }, None).await?; + my_coll.insert_one(doc! { "x" : 1 }).await?; // end-operation Ok(()) diff --git a/source/includes/fundamentals/code-snippets/transaction.rs b/source/includes/fundamentals/code-snippets/transaction.rs index f7d0698c..24f8982e 100644 --- a/source/includes/fundamentals/code-snippets/transaction.rs +++ b/source/includes/fundamentals/code-snippets/transaction.rs @@ -16,20 +16,21 @@ async fn insert_media(session: &mut ClientSession) -> Result<(), Error> { .database("db") .collection::("films"); - books_coll.insert_one_with_session( - doc! { - "name": "Sula", + books_coll + .insert_one(doc! { + "name": "Sula", "author": "Toni Morrison" - }, - None, - session - ).await?; + }) + .session(&mut *session) + .await?; - films_coll.insert_one_with_session( - doc! { "name": "Nostalgia", "year": 1983 }, - None, - session - ).await?; + films_coll + .insert_one(doc! { + "name": "Nostalgia", + "year": 1983 + }) + .session(&mut *session) + .await?; Ok(()) } @@ -41,9 +42,11 @@ async fn main() -> mongodb::error::Result<()> { let client = Client::with_uri_str(uri).await?; // begin-session - let mut session = client.start_session(None).await?; + let mut session = client.start_session().await?; + session - .with_transaction((), |session, _| insert_media(session).boxed(), None) + .start_transaction() + .and_run((), |session, _| insert_media(session).boxed()) .await?; println!("Successfully committed transaction!"); // end-session diff --git a/source/includes/fundamentals/code-snippets/tseries.rs b/source/includes/fundamentals/code-snippets/tseries.rs index 81c30555..a3e3c94d 100644 --- a/source/includes/fundamentals/code-snippets/tseries.rs +++ b/source/includes/fundamentals/code-snippets/tseries.rs @@ -18,16 +18,14 @@ async fn main() -> mongodb::error::Result<()> { .meta_field(Some("location".to_string())) .granularity(Some(TimeseriesGranularity::Minutes)) .build(); - - let coll_opts = CreateCollectionOptions::builder() - .timeseries(ts_opts) - .build(); - db.create_collection("sept2023", coll_opts).await?; + db.create_collection("sept2023") + .timeseries(ts_opts) + .await?; // end-create-ts // begin-list-colls - let mut coll_list = db.list_collections(None, None).await?; + let mut coll_list = db.list_collections().await?; while let Some(c) = coll_list.try_next().await? { println!("{:#?}", c); } diff --git a/source/includes/quick-start/code-snippets/connect-async.rs b/source/includes/quick-start/code-snippets/connect-async.rs index ef43982d..62535a16 100644 --- a/source/includes/quick-start/code-snippets/connect-async.rs +++ b/source/includes/quick-start/code-snippets/connect-async.rs @@ -17,7 +17,7 @@ async fn main() -> mongodb::error::Result<()> { let my_coll: Collection = database.collection("movies"); // Find a movie based on the title value - let my_movie = my_coll.find_one(doc! { "title": "The Perils of Pauline" }, None).await?; + let my_movie = my_coll.find_one(doc! { "title": "The Perils of Pauline" }).await?; // Print the document println!("Found a movie:\n{:#?}", my_movie); diff --git a/source/includes/quick-start/code-snippets/connect-sync.rs b/source/includes/quick-start/code-snippets/connect-sync.rs index e68657f9..a2ee1b83 100644 --- a/source/includes/quick-start/code-snippets/connect-sync.rs +++ b/source/includes/quick-start/code-snippets/connect-sync.rs @@ -15,7 +15,9 @@ fn main() -> mongodb::error::Result<()> { let my_coll: Collection = database.collection("movies"); // Find a movie based on the title value - let my_movie = my_coll.find_one(doc! { "title": "The Perils of Pauline" }, None)?; + let my_movie = my_coll + .find_one(doc! { "title": "The Perils of Pauline" }) + .run()?; // Print the document println!("Found a movie:\n{:#?}", my_movie); diff --git a/source/includes/usage-examples/code-snippets/count-async.rs b/source/includes/usage-examples/code-snippets/count-async.rs index c63d1ff4..5606cf19 100644 --- a/source/includes/usage-examples/code-snippets/count-async.rs +++ b/source/includes/usage-examples/code-snippets/count-async.rs @@ -11,10 +11,10 @@ async fn main() -> mongodb::error::Result<()> { .database("sample_restaurants") .collection("restaurants"); - let ct = my_coll.estimated_document_count(None).await?; + let ct = my_coll.estimated_document_count().await?; println!("Number of documents: {}", ct); - let ct = my_coll.count_documents(doc! { "name": doc! { "$regex": "Sunset" } }, None).await?; + let ct = my_coll.count_documents(doc! { "name": doc! { "$regex": "Sunset" } }).await?; println!("Number of matching documents: {}", ct); Ok(()) diff --git a/source/includes/usage-examples/code-snippets/count-sync.rs b/source/includes/usage-examples/code-snippets/count-sync.rs index 0d8ec623..b1e4e08d 100644 --- a/source/includes/usage-examples/code-snippets/count-sync.rs +++ b/source/includes/usage-examples/code-snippets/count-sync.rs @@ -12,10 +12,12 @@ fn main() -> mongodb::error::Result<()> { .database("sample_restaurants") .collection("restaurants"); - let ct = my_coll.estimated_document_count(None)?; + let ct = my_coll.estimated_document_count().run()?; println!("Number of documents: {}", ct); - let ct = my_coll.count_documents(doc! { "name": doc! { "$regex": "Sunset" } }, None)?; + let ct = my_coll + .count_documents(doc! { "name": doc! { "$regex": "Sunset" } }) + .run()?; println!("Number of matching documents: {}", ct); Ok(()) diff --git a/source/includes/usage-examples/code-snippets/delete-many-async.rs b/source/includes/usage-examples/code-snippets/delete-many-async.rs index a0f4807a..b1f5b233 100644 --- a/source/includes/usage-examples/code-snippets/delete-many-async.rs +++ b/source/includes/usage-examples/code-snippets/delete-many-async.rs @@ -20,7 +20,7 @@ async fn main() -> mongodb::error::Result<()> { ] }; - let result = my_coll.delete_many(filter, None).await?; + let result = my_coll.delete_many(filter).await?; println!("Deleted documents: {}", result.deleted_count); diff --git a/source/includes/usage-examples/code-snippets/delete-many-sync.rs b/source/includes/usage-examples/code-snippets/delete-many-sync.rs index 0b031e33..7565b1d0 100644 --- a/source/includes/usage-examples/code-snippets/delete-many-sync.rs +++ b/source/includes/usage-examples/code-snippets/delete-many-sync.rs @@ -18,7 +18,7 @@ fn main() -> mongodb::error::Result<()> { ] }; - let result = my_coll.delete_many(filter, None)?; + let result = my_coll.delete_many(filter).run()?; println!("Deleted documents: {}", result.deleted_count); diff --git a/source/includes/usage-examples/code-snippets/delete-one-async.rs b/source/includes/usage-examples/code-snippets/delete-one-async.rs index 449cd26d..5364ef2d 100644 --- a/source/includes/usage-examples/code-snippets/delete-one-async.rs +++ b/source/includes/usage-examples/code-snippets/delete-one-async.rs @@ -20,7 +20,7 @@ async fn main() -> mongodb::error::Result<()> { ] }; - let result = my_coll.delete_one(filter, None).await?; + let result = my_coll.delete_one(filter).await?; println!("Deleted documents: {}", result.deleted_count); diff --git a/source/includes/usage-examples/code-snippets/delete-one-sync.rs b/source/includes/usage-examples/code-snippets/delete-one-sync.rs index 08832a37..53a981d8 100644 --- a/source/includes/usage-examples/code-snippets/delete-one-sync.rs +++ b/source/includes/usage-examples/code-snippets/delete-one-sync.rs @@ -18,7 +18,7 @@ fn main() -> mongodb::error::Result<()> { ] }; - let result = my_coll.delete_one(filter, None)?; + let result = my_coll.delete_one(filter).run()?; println!("Deleted documents: {}", result.deleted_count); diff --git a/source/includes/usage-examples/code-snippets/distinct-async.rs b/source/includes/usage-examples/code-snippets/distinct-async.rs index 0a40697d..f753e8a7 100644 --- a/source/includes/usage-examples/code-snippets/distinct-async.rs +++ b/source/includes/usage-examples/code-snippets/distinct-async.rs @@ -14,7 +14,7 @@ async fn main() -> mongodb::error::Result<()> { .collection("restaurants"); let filter = doc! { "cuisine": "Turkish" }; - let boroughs = my_coll.distinct("borough", filter, None).await?; + let boroughs = my_coll.distinct("borough", filter).await?; println!("List of field values for 'borough':"); for b in boroughs.iter() { diff --git a/source/includes/usage-examples/code-snippets/distinct-sync.rs b/source/includes/usage-examples/code-snippets/distinct-sync.rs index c8f56618..16f77f7a 100644 --- a/source/includes/usage-examples/code-snippets/distinct-sync.rs +++ b/source/includes/usage-examples/code-snippets/distinct-sync.rs @@ -13,7 +13,7 @@ fn main() -> mongodb::error::Result<()> { .collection("restaurants"); let filter = doc! { "cuisine": "Turkish" }; - let boroughs = my_coll.distinct("borough", filter, None)?; + let boroughs = my_coll.distinct("borough", filter).run()?; println!("List of field values for 'borough':"); for b in boroughs.iter() { diff --git a/source/includes/usage-examples/code-snippets/find-async.rs b/source/includes/usage-examples/code-snippets/find-async.rs index d6d2aff8..86d46ba7 100644 --- a/source/includes/usage-examples/code-snippets/find-async.rs +++ b/source/includes/usage-examples/code-snippets/find-async.rs @@ -22,8 +22,7 @@ async fn main() -> mongodb::error::Result<()> { .collection("restaurants"); let mut cursor = my_coll.find( - doc! { "cuisine": "French" }, - None + doc! { "cuisine": "French" } ).await?; while let Some(doc) = cursor.try_next().await? { diff --git a/source/includes/usage-examples/code-snippets/find-one-async.rs b/source/includes/usage-examples/code-snippets/find-one-async.rs index 11d7714f..ed2c5c30 100644 --- a/source/includes/usage-examples/code-snippets/find-one-async.rs +++ b/source/includes/usage-examples/code-snippets/find-one-async.rs @@ -21,8 +21,7 @@ async fn main() -> mongodb::error::Result<()> { .collection("restaurants"); let result = my_coll.find_one( - doc! { "name": "Tompkins Square Bagels" }, - None + doc! { "name": "Tompkins Square Bagels" } ).await?; println!("{:#?}", result); diff --git a/source/includes/usage-examples/code-snippets/find-one-sync.rs b/source/includes/usage-examples/code-snippets/find-one-sync.rs index 737b0e46..d138e2af 100644 --- a/source/includes/usage-examples/code-snippets/find-one-sync.rs +++ b/source/includes/usage-examples/code-snippets/find-one-sync.rs @@ -19,9 +19,8 @@ fn main() -> mongodb::error::Result<()> { .collection("restaurants"); let result = my_coll.find_one( - doc! { "name": "Tompkins Square Bagels" }, - None - )?; + doc! { "name": "Tompkins Square Bagels" } + ).run()?; println!("{:#?}", result); diff --git a/source/includes/usage-examples/code-snippets/find-sync.rs b/source/includes/usage-examples/code-snippets/find-sync.rs index e73ec4d0..8dd49f6e 100644 --- a/source/includes/usage-examples/code-snippets/find-sync.rs +++ b/source/includes/usage-examples/code-snippets/find-sync.rs @@ -19,9 +19,8 @@ fn main() -> mongodb::error::Result<()> { .collection("restaurants"); let mut cursor = my_coll.find( - doc! { "cuisine": "French" }, - None - )?; + doc! { "cuisine": "French" } + ).run()?; for result in cursor { println!("{:?}", result?); diff --git a/source/includes/usage-examples/code-snippets/insert-many-async.rs b/source/includes/usage-examples/code-snippets/insert-many-async.rs index f0158383..8fdf5771 100644 --- a/source/includes/usage-examples/code-snippets/insert-many-async.rs +++ b/source/includes/usage-examples/code-snippets/insert-many-async.rs @@ -31,7 +31,7 @@ async fn main() -> mongodb::error::Result<()> { } ]; - let insert_many_result = my_coll.insert_many(docs, None).await?; + let insert_many_result = my_coll.insert_many(docs).await?; println!("Inserted documents with _ids:"); for (_key, value) in &insert_many_result.inserted_ids { println!("{}", value); diff --git a/source/includes/usage-examples/code-snippets/insert-many-sync.rs b/source/includes/usage-examples/code-snippets/insert-many-sync.rs index ce917931..cbfc7579 100644 --- a/source/includes/usage-examples/code-snippets/insert-many-sync.rs +++ b/source/includes/usage-examples/code-snippets/insert-many-sync.rs @@ -29,7 +29,7 @@ fn main() -> mongodb::error::Result<()> { } ]; - let insert_many_result = my_coll.insert_many(docs, None)?; + let insert_many_result = my_coll.insert_many(docs).run()?; println!("Inserted documents with _ids:"); for (_key, value) in &insert_many_result.inserted_ids { println!("{}", value); diff --git a/source/includes/usage-examples/code-snippets/insert-one-async.rs b/source/includes/usage-examples/code-snippets/insert-one-async.rs index 0b7497d2..6d672452 100644 --- a/source/includes/usage-examples/code-snippets/insert-one-async.rs +++ b/source/includes/usage-examples/code-snippets/insert-one-async.rs @@ -24,7 +24,7 @@ async fn main() -> mongodb::error::Result<()> { borough: "Queens".to_string(), }; - let res = my_coll.insert_one(doc, None).await?; + let res = my_coll.insert_one(doc).await?; println!("Inserted a document with _id: {}", res.inserted_id); Ok(()) diff --git a/source/includes/usage-examples/code-snippets/insert-one-sync.rs b/source/includes/usage-examples/code-snippets/insert-one-sync.rs index 305bd3f8..7983c3f7 100644 --- a/source/includes/usage-examples/code-snippets/insert-one-sync.rs +++ b/source/includes/usage-examples/code-snippets/insert-one-sync.rs @@ -23,7 +23,7 @@ fn main() -> mongodb::error::Result<()> { borough: "Queens".to_string(), }; - let res = my_coll.insert_one(doc, None)?; + let res = my_coll.insert_one(doc).run()?; println!("Inserted a document with _id: {}", res.inserted_id); Ok(()) diff --git a/source/includes/usage-examples/code-snippets/replace-async.rs b/source/includes/usage-examples/code-snippets/replace-async.rs index 37f9b9d8..223adea6 100644 --- a/source/includes/usage-examples/code-snippets/replace-async.rs +++ b/source/includes/usage-examples/code-snippets/replace-async.rs @@ -25,7 +25,7 @@ async fn main() -> mongodb::error::Result<()> { name: "Harvest Moon Café".to_string(), }; - let res = my_coll.replace_one(filter, replacement, None).await?; + let res = my_coll.replace_one(filter, replacement).await?; println!("Replaced documents: {}", res.modified_count); Ok(()) diff --git a/source/includes/usage-examples/code-snippets/replace-sync.rs b/source/includes/usage-examples/code-snippets/replace-sync.rs index 087e5dfa..cba70641 100644 --- a/source/includes/usage-examples/code-snippets/replace-sync.rs +++ b/source/includes/usage-examples/code-snippets/replace-sync.rs @@ -24,7 +24,7 @@ fn main() -> mongodb::error::Result<()> { name: "Harvest Moon Café".to_string(), }; - let res = my_coll.replace_one(filter, replacement, None)?; + let res = my_coll.replace_one(filter, replacement).run()?; println!("Replaced documents: {}", res.modified_count); Ok(()) diff --git a/source/includes/usage-examples/code-snippets/update-many-async.rs b/source/includes/usage-examples/code-snippets/update-many-async.rs index 71a010df..9d1f34d5 100644 --- a/source/includes/usage-examples/code-snippets/update-many-async.rs +++ b/source/includes/usage-examples/code-snippets/update-many-async.rs @@ -18,7 +18,7 @@ async fn main() -> mongodb::error::Result<()> { }; let update = doc! { "$set": doc! { "near_me": true } }; - let res = my_coll.update_many(filter, update, None).await?; + let res = my_coll.update_many(filter, update).await?; println!("Updated documents: {}", res.modified_count); Ok(()) diff --git a/source/includes/usage-examples/code-snippets/update-many-sync.rs b/source/includes/usage-examples/code-snippets/update-many-sync.rs index f4fc776f..51bb9ee7 100644 --- a/source/includes/usage-examples/code-snippets/update-many-sync.rs +++ b/source/includes/usage-examples/code-snippets/update-many-sync.rs @@ -19,7 +19,7 @@ fn main() -> mongodb::error::Result<()> { }; let update = doc! { "$set": doc! { "near_me": true } }; - let res = my_coll.update_many(filter, update, None)?; + let res = my_coll.update_many(filter, update).run()?; println!("Updated documents: {}", res.modified_count); Ok(()) diff --git a/source/includes/usage-examples/code-snippets/update-one-async.rs b/source/includes/usage-examples/code-snippets/update-one-async.rs index b696e5bf..44e43215 100644 --- a/source/includes/usage-examples/code-snippets/update-one-async.rs +++ b/source/includes/usage-examples/code-snippets/update-one-async.rs @@ -17,7 +17,7 @@ async fn main() -> mongodb::error::Result<()> { let filter = doc! { "name": "Spice Market" }; let update = doc! { "$set": doc! {"price": "$$$"} }; - let res = my_coll.update_one(filter, update, None).await?; + let res = my_coll.update_one(filter, update).await?; println!("Updated documents: {}", res.modified_count); Ok(()) diff --git a/source/includes/usage-examples/code-snippets/update-one-sync.rs b/source/includes/usage-examples/code-snippets/update-one-sync.rs index 4e746d68..42bdd72f 100644 --- a/source/includes/usage-examples/code-snippets/update-one-sync.rs +++ b/source/includes/usage-examples/code-snippets/update-one-sync.rs @@ -15,7 +15,7 @@ fn main() -> mongodb::error::Result<()> { let filter = doc! { "name": "Spice Market" }; let update = doc! { "$set": doc! {"price": "$$$"} }; - let res = my_coll.update_one(filter, update, None)?; + let res = my_coll.update_one(filter, update).run()?; println!("Updated documents: {}", res.modified_count); Ok(())