From 8bf2f9ee35061033741afea61e74f35690a00da4 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Fri, 15 Nov 2024 15:41:58 -0600 Subject: [PATCH 01/39] reorg --- config/redirects | 4 +- snooty.toml | 5 +- source/fundamentals/crud/write-operations.txt | 6 +- .../crud/write-operations/replace.txt | 231 +++++++++++++++ .../crud/write-operations/update.txt | 28 ++ .../crud/write-operations/update/arrays.txt | 270 ++++++++++++++++++ .../{modify.txt => update/fields.txt} | 216 +------------- 7 files changed, 546 insertions(+), 214 deletions(-) create mode 100644 source/fundamentals/crud/write-operations/replace.txt create mode 100644 source/fundamentals/crud/write-operations/update.txt create mode 100644 source/fundamentals/crud/write-operations/update/arrays.txt rename source/fundamentals/crud/write-operations/{modify.txt => update/fields.txt} (59%) diff --git a/config/redirects b/config/redirects index 5fa4c65e..6234d6cb 100644 --- a/config/redirects +++ b/config/redirects @@ -15,4 +15,6 @@ raw: ${prefix}/master -> ${base}/upcoming/ [*-master]: ${prefix}/${version}/fundamentals/data-formats/bson/ -> ${base}/${version}/fundamentals/bson/ [*-master]: ${prefix}/${version}/fundamentals/class-mapping/ -> ${base}/${version}/fundamentals/serialization/class-mapping/ [*-v2.30]: ${prefix}/${version}/upgrade/v2/ -> ${base}/${version}/upgrade/ -[*-v2.30]: ${prefix}/${version}/upgrade/v3/ -> ${base}/${version}/upgrade/ \ No newline at end of file +[*-v2.30]: ${prefix}/${version}/upgrade/v3/ -> ${base}/${version}/upgrade/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/modify/#replace-operation -> ${base}/${version}/fundamentals/crud/write-operations/replace/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/modify/ -> ${base}/${version}/fundamentals/crud/write-operations/ diff --git a/snooty.toml b/snooty.toml index 203bbe4b..6d7028cf 100644 --- a/snooty.toml +++ b/snooty.toml @@ -1,13 +1,14 @@ -name = "csharp" -title = "C#/.NET" toc_landing_pages = [ "/fundamentals/connection", "/fundamentals/crud", "/usage-examples", "/fundamentals", "/fundamentals/serialization", + "/fundamentals/crud/write-operations/update", "/upgrade", ] +name = "csharp" +title = "C#/.NET" intersphinx = [ "https://www.mongodb.com/docs/manual/objects.inv", diff --git a/source/fundamentals/crud/write-operations.txt b/source/fundamentals/crud/write-operations.txt index 3780689a..a4a25f13 100644 --- a/source/fundamentals/crud/write-operations.txt +++ b/source/fundamentals/crud/write-operations.txt @@ -11,11 +11,13 @@ Write Operations :caption: Write Operations Insert - Modify + Update + Replace Delete Bulk Write Operations - :ref:`csharp-insert-guide` -- :ref:`csharp-change-guide` +- :ref:`csharp-update-documents` +- :ref:`csharp-replace-documents` - :ref:`csharp-delete-guide` - :ref:`csharp-bulk-write` diff --git a/source/fundamentals/crud/write-operations/replace.txt b/source/fundamentals/crud/write-operations/replace.txt new file mode 100644 index 00000000..1bb2190f --- /dev/null +++ b/source/fundamentals/crud/write-operations/replace.txt @@ -0,0 +1,231 @@ +.. _csharp-replace-operation: +.. _csharp-replace-documents: + +================= +Replace Documents +================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: replace, synchronous, asynchronous + +Overview +-------- + +In this guide, you can learn how to use the {+driver-long+} to replace +documents in a MongoDB collection. + + + +The {+driver-short+} provides the following methods to modify documents, +each of which has an asynchronous and synchronous version: + +- ``ReplaceOneAsync()`` or ``ReplaceOne()`` + +You can perform a replace operation in MongoDB with the ``ReplaceOne()`` method. +This method removes all fields (except the ``_id`` field) from the first document that +matches the search criteria, then inserts the fields and values you specify into the +document. + +Required Parameters +~~~~~~~~~~~~~~~~~~~ + +The ``ReplaceOne()`` method requires the following parameters: + +- A query filter document, which determines which record to replace. +- A **replacement** document, which specifies the fields and values to insert in the new + document. If the documents in your collection are mapped to a {+language+} class, + the replacement document can be an instance of this class. + +Like in an update operation, you can use the ``Builders`` class in the {+driver-short+} +to create a query filter. +The following code sample uses ``Builders`` to create a query filter that searches +for restaurants with a ``name`` field value of "Pizza Town". The code also creates a new +``Restaurant`` object that will replace the first matched document. + +.. literalinclude:: /includes/code-examples/replace-one/ReplaceOne.cs + :language: csharp + :dedent: + :start-after: // start-replace-one + :end-before: // end-replace-one + +.. important:: + + The values of ``_id`` fields are immutable. If your replacement document specifies + a value for the ``_id`` field, it must match the ``_id`` value of the existing document. + +The following code shows how to use the asynchronous ``ReplaceOneAsync()`` method +or the synchronous ``ReplaceOne()`` method to replace one document. + +.. tabs:: + + .. tab:: Asynchronous + :tabid: replace-one-async + + .. code-block:: csharp + :copyable: true + + var result = await _restaurantsCollection.ReplaceOneAsync(filter, newRestaurant); + + .. tab:: Synchronous + :tabid: replace-one-sync + + .. code-block:: csharp + :copyable: true + + var result = _restaurantsCollection.ReplaceOne(filter, newRestaurant); + +.. tip:: + + Find runnable examples that use these methods under :ref:`Additional + Information `. + +Customize the Replace Operation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The ``ReplaceOne()`` method optionally accepts a ``ReplaceOptions`` object as an +additional parameter, which represents options you can use to configure the replace +operation. If you don't specify any ``ReplaceOptions`` properties, the driver does +not customize the replace operation. + +The ``ReplaceOptions`` type allows you to configure options with the +following properties: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Property + - Description + + * - ``BypassDocumentValidation`` + - | Specifies whether the replace operation bypasses document validation. This lets you + replace documents that don't meet the schema validation requirements, if any + exist. See :manual:`the MongoDB server manual` + for more information on schema validation. + + * - ``Collation`` + - | Specifies the kind of language collation to use when sorting + results. See :manual:`the MongoDB server manual` + for more information on collation. + + * - ``Comment`` + - | Gets or sets the user-provided comment for the operation. + See :manual:`the MongoDB server manual` + for more information. + + * - ``Hint`` + - | Gets or sets the index to use to scan for documents. + See :manual:`the MongoDB server manual` + for more information. + + * - ``IsUpsert`` + - | Specifies whether the replace operation performs an upsert operation if no + documents match the query filter. + See :manual:`the MongoDB server manual ` + for more information. + + * - ``Let`` + - | Gets or sets the let document. + See :manual:`the MongoDB server manual ` + for more information. + +Return Value +~~~~~~~~~~~~ + +The ``ReplaceOne()`` method returns a ``ReplaceOneResult`` +object. The ``ReplaceOneResult`` type contains the following properties: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Property + - Description + + * - ``IsAcknowledged`` + - | Indicates whether the replace operation was acknowledged by MongoDB. + + * - ``IsModifiedCountAvailable`` + - | Indicates whether you can read the count of replaced records on the + ``ReplaceOneResult``. + + * - ``MatchedCount`` + - | The number of documents that matched the query filter, regardless of + whether one was replaced. + + * - ``ModifiedCount`` + - | The number of documents replaced by the replace operation. + + * - ``UpsertedId`` + - | The ID of the document that was upserted in the database, if the driver + performed an upsert. + +Example +~~~~~~~ + +The following code uses the ``ReplaceOne()`` method to find the first document where the +``name`` field has the value "Pizza Town", then replaces this document +with a new ``Restaurant`` document named "Food World". Because the ``IsUpsert`` option is +set to ``true``, the driver inserts a new document if the query filter doesn't +match any existing documents. + +.. io-code-block:: + :copyable: true + + .. input:: + :language: csharp + + var filter = Builders.Filter.Eq(restaurant => restaurant.Name, "Pizza Town"); + + Restaurant newRestaurant = new() + { + Name = "Food World", + Cuisine = "American", + Address = new BsonDocument + { + {"street", "Food St"}, + {"zipcode", "10003"}, + }, + Borough = "Manhattan", + }; + + ReplaceOptions opts = new ReplaceOptions() + { + Comment = new BsonString("Restaurant replaced for {+driver-short+} Fundamentals"), + IsUpsert = true + }; + + Console.WriteLine("Replacing document..."); + var result = _restaurantsCollection.ReplaceOne(filter, newRestaurant, opts); + + Console.WriteLine($"Replaced documents: {result.ModifiedCount}"); + Console.WriteLine($"Result acknowledged? {result.IsAcknowledged}"); + + .. output:: + :language: none + :visible: false + + Replacing document... + Replaced documents: 1 + Result acknowledged? True + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +* `ReplaceOne() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.ReplaceOne.html>`__ +* `ReplaceOneAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.ReplaceOneAsync.html>`__ +* `ReplaceOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ReplaceOptions.html>`__ +* `ReplaceOneResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ReplaceOneResult.html>`__ \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations/update.txt b/source/fundamentals/crud/write-operations/update.txt new file mode 100644 index 00000000..9a99db52 --- /dev/null +++ b/source/fundamentals/crud/write-operations/update.txt @@ -0,0 +1,28 @@ +.. _csharp-change-guide: +.. _csharp-update-documents: + +================ +Update Documents +================ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: update, synchronous, asynchronous, bulk + +.. toctree:: + :caption: Update Documents + + Fields + Arrays + +Overview +-------- diff --git a/source/fundamentals/crud/write-operations/update/arrays.txt b/source/fundamentals/crud/write-operations/update/arrays.txt new file mode 100644 index 00000000..3d1a7e7a --- /dev/null +++ b/source/fundamentals/crud/write-operations/update/arrays.txt @@ -0,0 +1,270 @@ +.. _csharp-update-arrays: + +============= +Update Arrays +============= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: synchronous, asynchronous + +Overview +-------- + +In this guide, you can learn how to update arrays in a document with the +MongoDB Java driver. + +To update an array, you must do the following: + +- Specify the update you want to perform +- Specify what array elements to apply your update to +- Perform an update operation using these specifications + +Sample Document +~~~~~~~~~~~~~~~ + +The following sections feature examples that update this sample +document: + +.. code-block:: json + + { "_id": 1, "color": "green", "qty": [8, 12, 18] } + +The examples on this page use the ``findOneAndUpdate()`` method of the +``MongoCollection`` class to retrieve and update the document. Each +example uses an instance of the ``FindOneAndUpdateOptions`` class to +have MongoDB retrieve the document after the update occurs. For +more information on the ``findOneAndUpdate()`` method, see our +:doc:`Compound Operations guide `. + +Specifying an Update +-------------------- + +To specify an update, use the ``Updates`` builder. The ``Updates`` +builder provides static utility methods to construct update +specifications. For more information about using the ``Updates`` builder with +arrays, see our :ref:`guide on the Updates builder `. + +The following example performs these actions: + +- Query for the sample document +- Append "17" to the ``qty`` array in the document that matches the query filter + +.. literalinclude:: /includes/fundamentals/code-snippets/UpdateArray.java + :language: java + :dedent: + :start-after: begin pushElementsExample + :end-before: end pushElementsExample + +The preceding example updates the original document to the following state: + +.. code-block:: json + :copyable: false + + { "_id": 1, "color": "green", "qty": [8, 12, 18, 17] } + +Specifying Array Elements +------------------------- + +You can specify which array elements to update using a positional +operator. Positional operators can specify the first, all, or certain +array elements to update. + +To specify elements in an array with positional operators, use **dot +notation**. Dot notation is a property access syntax for navigating BSON +objects. + +For additional information, see the Server Manual Entry on +:manual:`dot notation `. + +The First Matching Array Element +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To update the first array element that matches your query filter, use the +positional ``$`` operator. The array field must appear as part of your +query filter to use the positional ``$`` operator. + +Example +``````` + +The following example performs these actions: + +- Query for a document with a ``qty`` field containing the value "18" +- Decrement the first array value in the document that matches the query filter by "3" + +.. literalinclude:: /includes/fundamentals/code-snippets/UpdateArray.java + :language: java + :dedent: + :start-after: begin updateValueExample + :end-before: end updateValueExample + +The preceding example updates the original document to the following state: + +.. code-block:: json + :copyable: false + + { "_id": 1, "color": "green", "qty": [8, 12, 15] } + +For more information about the methods and operators mentioned in this section, +see the following resources: + +- :manual:`Positional $ Operator ` Server Manual Entry +- `inc() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#inc(java.lang.String,java.lang.Number)>`__ API Documentation + +Matching All Array Elements +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To update all elements in an array, use the all positional ``$[]`` operator. + +Example +``````` + +The following example performs these actions: + +- Query for the sample document +- Multiply array elements matching the query filter by "2" + +.. literalinclude:: /includes/fundamentals/code-snippets/UpdateArray.java + :language: java + :dedent: + :start-after: begin updateAllElementsExample + :end-before: end updateAllElementsExample + +The preceding example updates the original document to the following state: + +.. code-block:: json + :copyable: false + + { "_id": 1, "color": "green", "qty": [16, 24, 36] } + +For more information about the methods and operators mentioned in this section, +see the following resources: + +- :manual:`All Positional $[] Operator ` Server Manual Entry +- `mul() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#mul(java.lang.String,java.lang.Number)>`__ API Documentation + +Matching Multiple Array Elements +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To update array elements that match a filter, use the +filtered positional ``$[]`` operator. You must include an +array filter in your update operation to specify which array elements to +update. + +The ```` is the name you give your array filter. This value +must begin with a lowercase letter and contain only alphanumeric +characters. + +Example +``````` + +The following example performs these actions: + +- Query for the sample document +- Set an array filter to search for values less than "15" +- Increment array elements matching the query filter by "5" + +.. literalinclude:: /includes/fundamentals/code-snippets/UpdateArray.java + :language: java + :dedent: + :start-after: begin updateValueOptionsExample + :end-before: end updateValueOptionsExample + +The preceding example updates the original document to the following state: + +.. code-block:: json + :copyable: false + + { "_id": 1, "color": "green", "qty": [13, 17, 18] } + +For more information about the methods and operators mentioned in this section, +see the following resources: + +- :manual:`Filtered Positional $[\] Operator ` Server Manual Entry +- `inc() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#inc(java.lang.String,java.lang.Number)>`__ API Documentation + + + + +Updating Documents with LINQ3 +----------------------------- + + +LINQ syntax contains a positional operator (``$``) that you can use to update elements in an array field. +Previous versions of the {+driver-short+} supported both the LINQ2 and LINQ3 providers. +In LINQ2, you could use ``-1`` to indicate use of the positional operator. + +For example, the ``Restaurant`` class contains an array field named ``Grades`` that +contains multiple ``GradeEntry`` elements. The following code sample uses LINQ2 to update the +``Grade`` field of the first element in the ``Grades`` array: + +.. code-block:: csharp + :linenos: + + var anArrayId = ObjectId.GenerateNewId(); + var another = new Restaurant + { + Id = ObjectId.GenerateNewId(), + AnArrayMember = new List + { + new AnArrayClass { Id = anArrayId, Deleted = false } + } + }; + + await collection.UpdateOneAsync( + r => r.Id == "targetId" && r.AnArrayMember.Any(l => l.Id == anArrayId), + Builders.Update.Set(l => l.AnArrayMember.ElementAt(-1).Deleted, true)); + +.. code-block:: csharp + :linenos: + + var anArrayId = ObjectId.GenerateNewId(); + var another = new Restaurant + { + Id = ObjectId.GenerateNewId(), + AnArrayMember = new List + { + new AnArrayClass { Id = anArrayId, Deleted = false } + } + }; + + await collection.UpdateOneAsync( + r => r.Id == "targetId" && r.AnArrayMember.Any(l => l.Id == anArrayId), + Builders.Update.Set(l => l.AnArrayMember.ElementAt(-1).Deleted, true)); + +This no longer works in LINQ3. Instead, you must use the following syntax: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Elements to Match + * - LINQ Syntax + - {+driver-short+} Syntax + + * - First matching element + * - ``array.$`` + - | Specifies the positional operator in LINQ3. + See :manual:`the MongoDB server manual` + for more information. + + * - All elements + * - ``array.$[]`` + - | Specifies the positional operator in LINQ3. + See :manual:`the MongoDB server manual` + for more information. + + * - All matching elements + * - ``array.$[]`` + - | Specifies the positional operator in LINQ3. + See :manual:`the MongoDB server manual` + for more information. \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations/modify.txt b/source/fundamentals/crud/write-operations/update/fields.txt similarity index 59% rename from source/fundamentals/crud/write-operations/modify.txt rename to source/fundamentals/crud/write-operations/update/fields.txt index 7d187cd7..c6b80c5c 100644 --- a/source/fundamentals/crud/write-operations/modify.txt +++ b/source/fundamentals/crud/write-operations/update/fields.txt @@ -1,8 +1,8 @@ -.. _csharp-change-guide: +.. _csharp-update-fields: -================ -Modify Documents -================ +============= +Update Fields +============= .. contents:: On this page :local: @@ -15,23 +15,19 @@ Modify Documents :values: reference .. meta:: - :keywords: update, replace, synchronous, asynchronous, bulk + :keywords: synchronous, asynchronous Overview -------- In this guide, you can learn how to use the {+driver-long+} to modify -documents in a MongoDB collection by performing the following operations: - -- :ref:`Update Operations ` -- :ref:`Replace Operations ` +documents in a MongoDB collection by performing update operations. The {+driver-short+} provides the following methods to modify documents, each of which has an asynchronous and synchronous version: - ``UpdateOneAsync()`` or ``UpdateOne()`` - ``UpdateManyAsync()`` or ``UpdateMany()`` -- ``ReplaceOneAsync()`` or ``ReplaceOne()`` .. tip:: Interactive Lab @@ -305,210 +301,16 @@ match any existing documents. ``UpdateMany()``, the driver would update only the first of the matched documents. -.. _csharp-replace-operation: - -Replace Operation ------------------ - -You can perform a replace operation in MongoDB with the ``ReplaceOne()`` method. -This method removes all fields (except the ``_id`` field) from the first document that -matches the search criteria, then inserts the fields and values you specify into the -document. - -Required Parameters -~~~~~~~~~~~~~~~~~~~ - -The ``ReplaceOne()`` method requires the following parameters: - -- A query filter document, which determines which record to replace. -- A **replacement** document, which specifies the fields and values to insert in the new - document. If the documents in your collection are mapped to a {+language+} class, - the replacement document can be an instance of this class. - -Like in an update operation, you can use the ``Builders`` class in the {+driver-short+} -to create a query filter. -The following code sample uses ``Builders`` to create a query filter that searches -for restaurants with a ``name`` field value of "Pizza Town". The code also creates a new -``Restaurant`` object that will replace the first matched document. - -.. literalinclude:: /includes/code-examples/replace-one/ReplaceOne.cs - :language: csharp - :dedent: - :start-after: // start-replace-one - :end-before: // end-replace-one - -.. important:: - - The values of ``_id`` fields are immutable. If your replacement document specifies - a value for the ``_id`` field, it must match the ``_id`` value of the existing document. - -The following code shows how to use the asynchronous ``ReplaceOneAsync()`` method -or the synchronous ``ReplaceOne()`` method to replace one document. - -.. tabs:: - - .. tab:: Asynchronous - :tabid: replace-one-async - - .. code-block:: csharp - :copyable: true - - var result = await _restaurantsCollection.ReplaceOneAsync(filter, newRestaurant); - - .. tab:: Synchronous - :tabid: replace-one-sync - - .. code-block:: csharp - :copyable: true - - var result = _restaurantsCollection.ReplaceOne(filter, newRestaurant); - -.. tip:: - - Find runnable examples that use these methods under :ref:`Additional - Information `. - -Customize the Replace Operation -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The ``ReplaceOne()`` method optionally accepts a ``ReplaceOptions`` object as an -additional parameter, which represents options you can use to configure the replace -operation. If you don't specify any ``ReplaceOptions`` properties, the driver does -not customize the replace operation. - -The ``ReplaceOptions`` type allows you to configure options with the -following properties: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Property - - Description - - * - ``BypassDocumentValidation`` - - | Specifies whether the replace operation bypasses document validation. This lets you - replace documents that don't meet the schema validation requirements, if any - exist. See :manual:`the MongoDB server manual` - for more information on schema validation. - - * - ``Collation`` - - | Specifies the kind of language collation to use when sorting - results. See :manual:`the MongoDB server manual` - for more information on collation. - - * - ``Comment`` - - | Gets or sets the user-provided comment for the operation. - See :manual:`the MongoDB server manual` - for more information. - - * - ``Hint`` - - | Gets or sets the index to use to scan for documents. - See :manual:`the MongoDB server manual` - for more information. - - * - ``IsUpsert`` - - | Specifies whether the replace operation performs an upsert operation if no - documents match the query filter. - See :manual:`the MongoDB server manual ` - for more information. - - * - ``Let`` - - | Gets or sets the let document. - See :manual:`the MongoDB server manual ` - for more information. - -Return Value -~~~~~~~~~~~~ - -The ``ReplaceOne()`` method returns a ``ReplaceOneResult`` -object. The ``ReplaceOneResult`` type contains the following properties: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Property - - Description - - * - ``IsAcknowledged`` - - | Indicates whether the replace operation was acknowledged by MongoDB. - - * - ``IsModifiedCountAvailable`` - - | Indicates whether you can read the count of replaced records on the - ``ReplaceOneResult``. - - * - ``MatchedCount`` - - | The number of documents that matched the query filter, regardless of - whether one was replaced. - - * - ``ModifiedCount`` - - | The number of documents replaced by the replace operation. - - * - ``UpsertedId`` - - | The ID of the document that was upserted in the database, if the driver - performed an upsert. - -Example -~~~~~~~ - -The following code uses the ``ReplaceOne()`` method to find the first document where the -``name`` field has the value "Pizza Town", then replaces this document -with a new ``Restaurant`` document named "Food World". Because the ``IsUpsert`` option is -set to ``true``, the driver inserts a new document if the query filter doesn't -match any existing documents. - -.. io-code-block:: - :copyable: true - - .. input:: - :language: csharp - - var filter = Builders.Filter.Eq(restaurant => restaurant.Name, "Pizza Town"); - - Restaurant newRestaurant = new() - { - Name = "Food World", - Cuisine = "American", - Address = new BsonDocument - { - {"street", "Food St"}, - {"zipcode", "10003"}, - }, - Borough = "Manhattan", - }; - - ReplaceOptions opts = new ReplaceOptions() - { - Comment = new BsonString("Restaurant replaced for {+driver-short+} Fundamentals"), - IsUpsert = true - }; - - Console.WriteLine("Replacing document..."); - var result = _restaurantsCollection.ReplaceOne(filter, newRestaurant, opts); - - Console.WriteLine($"Replaced documents: {result.ModifiedCount}"); - Console.WriteLine($"Result acknowledged? {result.IsAcknowledged}"); - - .. output:: - :language: none - :visible: false - - Replacing document... - Replaced documents: 1 - Result acknowledged? True - .. _csharp-change-info: Additional Information ---------------------- -For runnable examples of the update and replace operations, see the following usage +For runnable examples of the update operations, see the following usage examples: - :ref:`csharp-update-one` - :ref:`csharp-update-many` -- :ref:`csharp-replace-one` To learn more about creating query filters, see the :ref:`csharp-specify-query` guide. @@ -524,10 +326,6 @@ guide, see the following API documentation: * `UpdateManyAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateManyAsync.html>`__ * `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ * `UpdateResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateResult.html>`__ -* `ReplaceOne() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.ReplaceOne.html>`__ -* `ReplaceOneAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.ReplaceOneAsync.html>`__ -* `ReplaceOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ReplaceOptions.html>`__ -* `ReplaceOneResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ReplaceOneResult.html>`__ .. _csharp-update-instruqt-lab: From 9b236ca6fc272d73724bc14167853e3897b8179e Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Mon, 18 Nov 2024 15:12:10 -0600 Subject: [PATCH 02/39] replace page --- .../crud/write-operations/replace.txt | 268 ++++++++++-------- .../code-examples/replace-one/ReplaceOne.cs | 50 +++- .../replace-one/ReplaceOneAsync.cs | 42 ++- 3 files changed, 218 insertions(+), 142 deletions(-) diff --git a/source/fundamentals/crud/write-operations/replace.txt b/source/fundamentals/crud/write-operations/replace.txt index 1bb2190f..7862a0ae 100644 --- a/source/fundamentals/crud/write-operations/replace.txt +++ b/source/fundamentals/crud/write-operations/replace.txt @@ -24,81 +24,106 @@ Overview In this guide, you can learn how to use the {+driver-long+} to replace documents in a MongoDB collection. +The {+driver-short+} provides the ``ReplaceOne()`` and ``ReplaceOneAsync()`` methods. +These methods remove all fields (except the ``_id`` field) from the first document that +matches the search criteria, then insert the fields and values you specify into the +document. +Sample Data +~~~~~~~~~~~ -The {+driver-short+} provides the following methods to modify documents, -each of which has an asynchronous and synchronous version: +The examples in this guide use the ``restaurants`` collection +in the ``sample_restaurants`` database provided in the :atlas:`Atlas sample datasets `. +To learn how to create a free MongoDB Atlas cluster and load the sample datasets, +see the :ref:``. -- ``ReplaceOneAsync()`` or ``ReplaceOne()`` +.. include:: /includes/convention-pack-note.rst -You can perform a replace operation in MongoDB with the ``ReplaceOne()`` method. -This method removes all fields (except the ``_id`` field) from the first document that -matches the search criteria, then inserts the fields and values you specify into the -document. +Replace Methods +--------------- -Required Parameters -~~~~~~~~~~~~~~~~~~~ +To replace a document in a collection, call the ``ReplaceOne()`` or ``ReplaceOneAsync()`` +method. These methods accept the following parameters: -The ``ReplaceOne()`` method requires the following parameters: +.. list-table:: + :widths: 30 70 + :header-rows: 1 -- A query filter document, which determines which record to replace. -- A **replacement** document, which specifies the fields and values to insert in the new - document. If the documents in your collection are mapped to a {+language+} class, - the replacement document can be an instance of this class. + * - Parameter + - Description -Like in an update operation, you can use the ``Builders`` class in the {+driver-short+} -to create a query filter. -The following code sample uses ``Builders`` to create a query filter that searches -for restaurants with a ``name`` field value of "Pizza Town". The code also creates a new -``Restaurant`` object that will replace the first matched document. + * - ``filter`` + - A *query filter* document that specifies the record to replace. You can use the + ``Builders`` class to create a query filter. -.. literalinclude:: /includes/code-examples/replace-one/ReplaceOne.cs - :language: csharp - :dedent: - :start-after: // start-replace-one - :end-before: // end-replace-one + **Data Type:** `FilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ ```` -.. important:: + * - ``replacement`` + - A *replacement* document, which specifies the fields and values to insert in the new + document. If the documents in your collection are mapped to a {+language+} class, + the replacement document can be an instance of this class. - The values of ``_id`` fields are immutable. If your replacement document specifies - a value for the ``_id`` field, it must match the ``_id`` value of the existing document. + **Data Type:** ``TDocument`` -The following code shows how to use the asynchronous ``ReplaceOneAsync()`` method -or the synchronous ``ReplaceOne()`` method to replace one document. + * - ``options`` + - *Optional.* An instance of the ``ReplaceOptions`` class that specifies the + configuration for the replace operation. The default value is ``null``. -.. tabs:: + **Data Type:** `ReplaceOptions <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.ReplaceOptions.html>`__ - .. tab:: Asynchronous - :tabid: replace-one-async + * - ``cancellationToken`` + - *Optional.* A token that you can use to cancel the operation. - .. code-block:: csharp - :copyable: true + **Data type**: `CancellationToken `__ + +The following code example performs the following steps: + +1. Uses the ``Builders`` class to create a query filter. The filter matches all + documents where the ``cuisine`` field has the value ``"Pizza"``. +#. Creates a new ``Restaurant`` object. +#. Calls the ``ReplaceOne()`` method on the ``restaurants`` collection. This operation + find the first matching document in the collection and replaces it with the newly created + document. - var result = await _restaurantsCollection.ReplaceOneAsync(filter, newRestaurant); +Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the +corresponding code. + +.. tabs:: .. tab:: Synchronous :tabid: replace-one-sync - .. code-block:: csharp + .. literalinclude:: /includes/code-examples/replace-one/ReplaceOne.cs + :language: csharp :copyable: true + :dedent: + :start-after: // start-replace-one-sync + :end-before: // end-replace-one-sync + + .. tab:: Asynchronous + :tabid: replace-one-async - var result = _restaurantsCollection.ReplaceOne(filter, newRestaurant); + .. literalinclude:: /includes/code-examples/replace-one/ReplaceOneAsync.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-replace-one-async + :end-before: // end-replace-one-async -.. tip:: +.. important:: - Find runnable examples that use these methods under :ref:`Additional - Information `. + The values of ``_id`` fields are immutable. If your replacement document specifies + a value for the ``_id`` field, it must match the ``_id`` value of the existing document. Customize the Replace Operation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The ``ReplaceOne()`` method optionally accepts a ``ReplaceOptions`` object as an +The ``ReplaceOne()`` and ``ReplaceOneAsync()`` methods optionally accept a +``ReplaceOptions`` object as an additional parameter, which represents options you can use to configure the replace -operation. If you don't specify any ``ReplaceOptions`` properties, the driver does -not customize the replace operation. +operation. -The ``ReplaceOptions`` type allows you to configure options with the -following properties: +The ``ReplaceOptions`` class contains the following properties: .. list-table:: :widths: 30 70 @@ -108,25 +133,33 @@ following properties: - Description * - ``BypassDocumentValidation`` - - | Specifies whether the replace operation bypasses document validation. This lets you - replace documents that don't meet the schema validation requirements, if any - exist. See :manual:`the MongoDB server manual` - for more information on schema validation. + - Specifies whether the replace operation bypasses document validation. This lets you + replace documents that don't meet the schema validation requirements, if any + exist. See :manual:`the MongoDB server manual` + for more information on schema validation. + + **Data Type:** ``bool?`` * - ``Collation`` - - | Specifies the kind of language collation to use when sorting - results. See :manual:`the MongoDB server manual` - for more information on collation. + - Specifies the kind of language collation to use when sorting + results. See :manual:`the MongoDB server manual` + for more information on collation. + + **Data Type:** `Collation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Collation.html>`__ * - ``Comment`` - - | Gets or sets the user-provided comment for the operation. - See :manual:`the MongoDB server manual` - for more information. + - Gets or sets the user-provided comment for the operation. + See :manual:`the MongoDB server manual` + for more information. + + **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ * - ``Hint`` - - | Gets or sets the index to use to scan for documents. - See :manual:`the MongoDB server manual` - for more information. + - Gets or sets the index to use to scan for documents. + See :manual:`the MongoDB server manual` + for more information. + + **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ * - ``IsUpsert`` - | Specifies whether the replace operation performs an upsert operation if no @@ -134,16 +167,48 @@ following properties: See :manual:`the MongoDB server manual ` for more information. + **Data Type:** ``bool`` + * - ``Let`` - - | Gets or sets the let document. - See :manual:`the MongoDB server manual ` - for more information. + - Gets or sets the let document. + See :manual:`the MongoDB server manual ` + for more information. + + **Data Type:** `BsonDocument <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonDocument.html>`__ + +The following example performs the same steps as the preceding example, but also uses +the ``BypassDocumentValidation`` option to bypass any schema validation requirements. +Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding +code. + +.. tabs:: + + .. tab:: Synchronous + :tabid: replace-one-sync-with-options + + .. literalinclude:: /includes/code-examples/replace-one/ReplaceOne.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-replace-one-sync-with-options + :end-before: // end-replace-one-sync-with-options + + .. tab:: Asynchronous + :tabid: replace-one-async-with-options + + .. literalinclude:: /includes/code-examples/replace-one/ReplaceOneAsync.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-replace-one-async-with-options + :end-before: // end-replace-one-async-with-options Return Value ~~~~~~~~~~~~ The ``ReplaceOne()`` method returns a ``ReplaceOneResult`` -object. The ``ReplaceOneResult`` type contains the following properties: +object, and the ``ReplaceOneAsync()`` method returns a ``Task`` object. +The ``ReplaceOneResult`` class contains the following properties: .. list-table:: :widths: 30 70 @@ -153,77 +218,38 @@ object. The ``ReplaceOneResult`` type contains the following properties: - Description * - ``IsAcknowledged`` - - | Indicates whether the replace operation was acknowledged by MongoDB. + - Indicates whether the replace operation was acknowledged by MongoDB. + **Data Type:** ``bool`` + * - ``IsModifiedCountAvailable`` - - | Indicates whether you can read the count of replaced records on the - ``ReplaceOneResult``. + - Indicates whether you can read the count of replaced records on the + ``ReplaceOneResult``. + + **Data Type:** ``bool`` * - ``MatchedCount`` - - | The number of documents that matched the query filter, regardless of - whether one was replaced. + - The number of documents that matched the query filter, regardless of + whether one was replaced. + + **Data Type:** ``long`` * - ``ModifiedCount`` - - | The number of documents replaced by the replace operation. + - The number of documents replaced by the replace operation. + + **Data Type:** ``long`` * - ``UpsertedId`` - - | The ID of the document that was upserted in the database, if the driver - performed an upsert. - -Example -~~~~~~~ - -The following code uses the ``ReplaceOne()`` method to find the first document where the -``name`` field has the value "Pizza Town", then replaces this document -with a new ``Restaurant`` document named "Food World". Because the ``IsUpsert`` option is -set to ``true``, the driver inserts a new document if the query filter doesn't -match any existing documents. - -.. io-code-block:: - :copyable: true - - .. input:: - :language: csharp - - var filter = Builders.Filter.Eq(restaurant => restaurant.Name, "Pizza Town"); - - Restaurant newRestaurant = new() - { - Name = "Food World", - Cuisine = "American", - Address = new BsonDocument - { - {"street", "Food St"}, - {"zipcode", "10003"}, - }, - Borough = "Manhattan", - }; - - ReplaceOptions opts = new ReplaceOptions() - { - Comment = new BsonString("Restaurant replaced for {+driver-short+} Fundamentals"), - IsUpsert = true - }; - - Console.WriteLine("Replacing document..."); - var result = _restaurantsCollection.ReplaceOne(filter, newRestaurant, opts); - - Console.WriteLine($"Replaced documents: {result.ModifiedCount}"); - Console.WriteLine($"Result acknowledged? {result.IsAcknowledged}"); - - .. output:: - :language: none - :visible: false - - Replacing document... - Replaced documents: 1 - Result acknowledged? True + - The ID of the document that was upserted in the database, if the driver + performed an upsert. + + **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ API Documentation ~~~~~~~~~~~~~~~~~ -To learn more about any of the methods or types discussed in this -guide, see the following API documentation: +To learn more about any of the methods and classes used on this page, +see the following API documentation: * `ReplaceOne() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.ReplaceOne.html>`__ * `ReplaceOneAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.ReplaceOneAsync.html>`__ diff --git a/source/includes/code-examples/replace-one/ReplaceOne.cs b/source/includes/code-examples/replace-one/ReplaceOne.cs index cb68232e..0efe398c 100644 --- a/source/includes/code-examples/replace-one/ReplaceOne.cs +++ b/source/includes/code-examples/replace-one/ReplaceOne.cs @@ -14,7 +14,8 @@ public class ReplaceOne public static void Main(string[] args) { - try { + try + { Setup(); // Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza" @@ -36,30 +37,27 @@ public static void Main(string[] args) _restaurantsCollection.ReplaceOneAsync(filter, oldPizzaRestaurant); Console.WriteLine("done."); - // Prints a message if any exceptions occur during the operation - } catch (MongoException me) { + // Prints a message if any exceptions occur during the operation + } + catch (MongoException me) + { Console.WriteLine("Unable to replace due to an error: " + me); } } private static ReplaceOneResult ReplaceOneRestaurant() { - // start-replace-one + // start-replace-one-sync // Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza" var filter = Builders.Filter .Eq(r => r.Cuisine, "Pizza"); - // Finds the ID of the first restaurant document that matches the filter - var oldPizzaRestaurant = _restaurantsCollection.Find(filter).First(); - var oldId = oldPizzaRestaurant.Id; - // Generates a new restaurant document Restaurant newPizzaRestaurant = new() { - Id = oldId, Name = "Mongo's Pizza", Cuisine = "Pizza", - Address = new() + Address = new Address() { Street = "Pizza St", ZipCode = "10003" @@ -69,7 +67,37 @@ private static ReplaceOneResult ReplaceOneRestaurant() // Replaces the existing restaurant document with the new document return _restaurantsCollection.ReplaceOne(filter, newPizzaRestaurant); - // end-replace-one + // end-replace-one-sync + } + + private static ReplaceOneResult ReplaceOneRestaurantWithOptions() + { + // start-replace-one-sync-with-options + // Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza" + var filter = Builders.Filter + .Eq(r => r.Cuisine, "Pizza"); + + // Generates a new restaurant document + Restaurant newPizzaRestaurant = new() + { + Name = "Mongo's Pizza", + Cuisine = "Pizza", + Address = new Address() + { + Street = "Pizza St", + ZipCode = "10003" + }, + Borough = "Manhattan", + }; + + var options = new ReplaceOptions + { + BypassDocumentValidation = true + }; + + // Replaces the existing restaurant document with the new document + return _restaurantsCollection.ReplaceOne(filter, newPizzaRestaurant, options); + // end-replace-one-sync-with-options } private static void Setup() diff --git a/source/includes/code-examples/replace-one/ReplaceOneAsync.cs b/source/includes/code-examples/replace-one/ReplaceOneAsync.cs index 2bba474c..2e3375ca 100644 --- a/source/includes/code-examples/replace-one/ReplaceOneAsync.cs +++ b/source/includes/code-examples/replace-one/ReplaceOneAsync.cs @@ -14,7 +14,8 @@ public class ReplaceOneAsync public static async Task Main(string[] args) { - try { + try + { Setup(); // Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza" @@ -36,30 +37,27 @@ public static async Task Main(string[] args) await _restaurantsCollection.ReplaceOneAsync(filter, oldPizzaRestaurant); Console.WriteLine("done."); - // Prints a message if any exceptions occur during the operation - } catch (MongoException me) { + // Prints a message if any exceptions occur during the operation + } + catch (MongoException me) + { Console.WriteLine("Unable to replace due to an error: " + me); } } - private static async Task ReplaceOneRestaurant() + private static async Task ReplaceOneRestaurantAsync() { // start-replace-one-async // Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza" var filter = Builders.Filter .Eq(r => r.Cuisine, "Pizza"); - // Finds the ID of the first restaurant document that matches the filter - var oldPizzaRestaurant = _restaurantsCollection.Find(filter).First(); - var oldId = oldPizzaRestaurant.Id; - // Generates a new restaurant document Restaurant newPizzaRestaurant = new() { - Id = oldId, Name = "Mongo's Pizza", Cuisine = "Pizza", - Address = new() + Address = new Address() { Street = "Pizza St", ZipCode = "10003" @@ -71,6 +69,30 @@ private static async Task ReplaceOneRestaurant() return await _restaurantsCollection.ReplaceOneAsync(filter, newPizzaRestaurant); // end-replace-one-async } + private static async Task ReplaceOneRestaurantAsyncWithOptions() + { + // start-replace-one-async-with-options + // Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza" + var filter = Builders.Filter + .Eq(r => r.Cuisine, "Pizza"); + + // Generates a new restaurant document + Restaurant newPizzaRestaurant = new() + { + Name = "Mongo's Pizza", + Cuisine = "Pizza", + Address = new Address() + { + Street = "Pizza St", + ZipCode = "10003" + }, + Borough = "Manhattan", + }; + + // Asynchronously replaces the existing restaurant document with the new document + return await _restaurantsCollection.ReplaceOneAsync(filter, newPizzaRestaurant); + // end-replace-one-async-with-options + } private static void Setup() { From f1bb6f152b4b29abf47a0f1baec555e557a47ba1 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Mon, 18 Nov 2024 18:23:09 -0600 Subject: [PATCH 03/39] wip --- .../crud/write-operations/replace.txt | 40 +++++++--- .../crud/write-operations/update/fields.txt | 80 +++++++++++-------- 2 files changed, 78 insertions(+), 42 deletions(-) diff --git a/source/fundamentals/crud/write-operations/replace.txt b/source/fundamentals/crud/write-operations/replace.txt index 7862a0ae..c173eb91 100644 --- a/source/fundamentals/crud/write-operations/replace.txt +++ b/source/fundamentals/crud/write-operations/replace.txt @@ -33,14 +33,33 @@ Sample Data ~~~~~~~~~~~ The examples in this guide use the ``restaurants`` collection -in the ``sample_restaurants`` database provided in the :atlas:`Atlas sample datasets `. -To learn how to create a free MongoDB Atlas cluster and load the sample datasets, -see the :ref:``. +from the ``sample_restaurants`` database. The documents in this +collection use the following ``Restaurant``, ``Address``, and ``GradeEntry`` +classes as models: + +.. literalinclude:: /includes/code-examples/Restaurant.cs + :language: csharp + :copyable: + :dedent: + +.. literalinclude:: /includes/code-examples/Address.cs + :language: csharp + :copyable: + :dedent: + +.. literalinclude:: /includes/code-examples/GradeEntry.cs + :language: csharp + :copyable: + :dedent: .. include:: /includes/convention-pack-note.rst -Replace Methods ---------------- +This collection is from the :atlas:`sample datasets ` provided +by Atlas. See the :ref:`` to learn how to create a free MongoDB cluster +and load this sample data. + +Replace One Document +-------------------- To replace a document in a collection, call the ``ReplaceOne()`` or ``ReplaceOneAsync()`` method. These methods accept the following parameters: @@ -53,10 +72,12 @@ method. These methods accept the following parameters: - Description * - ``filter`` - - A *query filter* document that specifies the record to replace. You can use the - ``Builders`` class to create a query filter. + - A *query filter* that specifies the document to replace. You can use the + ``Builders`` class to create a query filter.For more information about + query filters, see the + :manual:`{+mdb-server+} manual `. - **Data Type:** `FilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ ```` + **Data Type:** `FilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ * - ``replacement`` - A *replacement* document, which specifies the fields and values to insert in the new @@ -76,7 +97,8 @@ method. These methods accept the following parameters: **Data type**: `CancellationToken `__ -The following code example performs the following steps: +The following code example demonstrates how to perform a replace operation. The +code performs the following steps: 1. Uses the ``Builders`` class to create a query filter. The filter matches all documents where the ``cuisine`` field has the value ``"Pizza"``. diff --git a/source/fundamentals/crud/write-operations/update/fields.txt b/source/fundamentals/crud/write-operations/update/fields.txt index c6b80c5c..e4cacca4 100644 --- a/source/fundamentals/crud/write-operations/update/fields.txt +++ b/source/fundamentals/crud/write-operations/update/fields.txt @@ -20,14 +20,19 @@ Update Fields Overview -------- -In this guide, you can learn how to use the {+driver-long+} to modify -documents in a MongoDB collection by performing update operations. +.. note:: Updating Arrays -The {+driver-short+} provides the following methods to modify documents, -each of which has an asynchronous and synchronous version: + This page discusses how to update document fields that contain single values. + To learn how to update array values in MongoDB documents, see + :ref:``. -- ``UpdateOneAsync()`` or ``UpdateOne()`` -- ``UpdateManyAsync()`` or ``UpdateMany()`` +In this guide, you can learn how to use the {+driver-long+} to update the +values of fields in MongoDB documents. + +The {+driver-short+} provides the following methods to update fields: + +- ``UpdateOne()`` or ``UpdateOneAsync()`` +- ``UpdateMany()`` or ``UpdateManyAsync()`` .. tip:: Interactive Lab @@ -70,47 +75,56 @@ and load this sample data. .. _csharp-update-operation: -Update Operations ------------------ +Update One Document +------------------- -You can perform update operations in MongoDB with the following methods: +To update one or more fields in a MongoDB document, call the ``UpdateOne()`` or +``UpdateOneAsync()`` method. These methods accept the following parameters: -- ``UpdateOne()``, which updates *the first document* that matches the search criteria -- ``UpdateMany()``, which updates *all documents* that match the search criteria +.. list-table:: + :widths: 30 70 + :header-rows: 1 -Required Parameters -~~~~~~~~~~~~~~~~~~~ + * - Parameter + - Description -Each update method requires the following parameters: + * - ``filter`` + - A *query filter* that specifies the document to update. You can use the + ``Builders`` class to create a query filter. For more information about + query filters, see the + :manual:`{+mdb-server+} manual `. -- A **query filter** document, which determines which records to update. See the - :manual:`MongoDB server manual ` for - more information about query filters. -- An **update** document, which specifies the **update operator** (the kind of update to - perform) and the fields and values that should change. See the - :manual:`Field Update Operators Manual page` for a complete - list of update operators and their usage. + **Data Type:** `FilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ -The {+driver-short+} provides a ``Builders`` class that simplifies the creation of both -query filters and update documents. The following code sample uses ``Builders`` to create -two documents for use as parameters in an update operation: + * - ``update`` + - An instance of the ``UpdateDefinition`` class. This object specifies the kind of update + operation, the fields to update, and the new value for each field. For a complete + list of update operations, see + :manual:`Field Update Operators ` in the + {+mdb-server+} manual. -- A query filter that searches for restaurants with a ``cuisine`` field value of "Pizza" -- An update document that sets the value of the ``cuisine`` field of these restaurants - to "Pasta and breadsticks" + **Data Type:** `UpdateDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinition-1.html>`__ -.. literalinclude:: /includes/code-examples/update-many/UpdateMany.cs - :language: csharp - :dedent: - :start-after: // start-update-many - :end-before: // end-update-many + * - ``options`` + - *Optional.* An instance of the ``UpdateOptions`` class that specifies the + configuration for the update operation. The default value is ``null``. + + **Data Type:** `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ + + * - ``cancellationToken`` + - *Optional.* A token that you can use to cancel the operation. + + **Data type**: `CancellationToken `__ + +The following code example demonstrates how to perform an update operation. The +code performs the following steps: .. tip:: Aggregation Pipelines in Update Operations If you are using MongoDB Version 4.2 or later, you can use aggregation pipelines made up of a subset of aggregation stages in update operations. For more information on the aggregation stages MongoDB supports in - aggregation pipelines used in update operations, see our tutorial on building + aggregation pipelines used in update operations, see the tutorial about building :manual:`updates with aggregation pipelines `. Update One Document From 6fd6830045bbfaac61097f30901d849f7fabe752 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Wed, 20 Nov 2024 12:52:49 -0600 Subject: [PATCH 04/39] wip --- .../crud/write-operations/replace.txt | 8 +- .../crud/write-operations/update/arrays.txt | 78 -- .../crud/write-operations/update/fields.txt | 348 -------- .../write-operations/update/update-one.txt | 841 ++++++++++++++++++ .../code-examples/update-one/UpdateOne.cs | 56 +- .../update-one/UpdateOneAsync.cs | 16 +- 6 files changed, 901 insertions(+), 446 deletions(-) delete mode 100644 source/fundamentals/crud/write-operations/update/fields.txt create mode 100644 source/fundamentals/crud/write-operations/update/update-one.txt diff --git a/source/fundamentals/crud/write-operations/replace.txt b/source/fundamentals/crud/write-operations/replace.txt index c173eb91..d8bf2c14 100644 --- a/source/fundamentals/crud/write-operations/replace.txt +++ b/source/fundamentals/crud/write-operations/replace.txt @@ -184,10 +184,10 @@ The ``ReplaceOptions`` class contains the following properties: **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ * - ``IsUpsert`` - - | Specifies whether the replace operation performs an upsert operation if no - documents match the query filter. - See :manual:`the MongoDB server manual ` - for more information. + - Specifies whether the replace operation performs an upsert operation if no + documents match the query filter. + See :manual:`the MongoDB server manual ` + for more information. **Data Type:** ``bool`` diff --git a/source/fundamentals/crud/write-operations/update/arrays.txt b/source/fundamentals/crud/write-operations/update/arrays.txt index 3d1a7e7a..4c5ef23a 100644 --- a/source/fundamentals/crud/write-operations/update/arrays.txt +++ b/source/fundamentals/crud/write-operations/update/arrays.txt @@ -1,77 +1,3 @@ -.. _csharp-update-arrays: - -============= -Update Arrays -============= - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: synchronous, asynchronous - -Overview --------- - -In this guide, you can learn how to update arrays in a document with the -MongoDB Java driver. - -To update an array, you must do the following: - -- Specify the update you want to perform -- Specify what array elements to apply your update to -- Perform an update operation using these specifications - -Sample Document -~~~~~~~~~~~~~~~ - -The following sections feature examples that update this sample -document: - -.. code-block:: json - - { "_id": 1, "color": "green", "qty": [8, 12, 18] } - -The examples on this page use the ``findOneAndUpdate()`` method of the -``MongoCollection`` class to retrieve and update the document. Each -example uses an instance of the ``FindOneAndUpdateOptions`` class to -have MongoDB retrieve the document after the update occurs. For -more information on the ``findOneAndUpdate()`` method, see our -:doc:`Compound Operations guide `. - -Specifying an Update --------------------- - -To specify an update, use the ``Updates`` builder. The ``Updates`` -builder provides static utility methods to construct update -specifications. For more information about using the ``Updates`` builder with -arrays, see our :ref:`guide on the Updates builder `. - -The following example performs these actions: - -- Query for the sample document -- Append "17" to the ``qty`` array in the document that matches the query filter - -.. literalinclude:: /includes/fundamentals/code-snippets/UpdateArray.java - :language: java - :dedent: - :start-after: begin pushElementsExample - :end-before: end pushElementsExample - -The preceding example updates the original document to the following state: - -.. code-block:: json - :copyable: false - - { "_id": 1, "color": "green", "qty": [8, 12, 18, 17] } - Specifying Array Elements ------------------------- @@ -89,10 +15,6 @@ For additional information, see the Server Manual Entry on The First Matching Array Element ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -To update the first array element that matches your query filter, use the -positional ``$`` operator. The array field must appear as part of your -query filter to use the positional ``$`` operator. - Example ``````` diff --git a/source/fundamentals/crud/write-operations/update/fields.txt b/source/fundamentals/crud/write-operations/update/fields.txt deleted file mode 100644 index e4cacca4..00000000 --- a/source/fundamentals/crud/write-operations/update/fields.txt +++ /dev/null @@ -1,348 +0,0 @@ -.. _csharp-update-fields: - -============= -Update Fields -============= - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: synchronous, asynchronous - -Overview --------- - -.. note:: Updating Arrays - - This page discusses how to update document fields that contain single values. - To learn how to update array values in MongoDB documents, see - :ref:``. - -In this guide, you can learn how to use the {+driver-long+} to update the -values of fields in MongoDB documents. - -The {+driver-short+} provides the following methods to update fields: - -- ``UpdateOne()`` or ``UpdateOneAsync()`` -- ``UpdateMany()`` or ``UpdateManyAsync()`` - -.. tip:: Interactive Lab - - This page includes a short interactive lab that demonstrates how to - modify data by using the ``UpdateManyAsync()`` method. You can complete this - lab directly in your browser window without installing MongoDB or a code editor. - - To start the lab, click the :guilabel:`Open Interactive Tutorial` button at the - top of the page. To expand the lab to a full-screen format, click the - full-screen button (:guilabel:`â›¶`) in the top-right corner of the lab pane. - -Sample Data -~~~~~~~~~~~ - -The examples in this guide use the ``restaurants`` collection -from the ``sample_restaurants`` database. The documents in this -collection use the following ``Restaurant``, ``Address``, and ``GradeEntry`` -classes as models: - -.. literalinclude:: /includes/code-examples/Restaurant.cs - :language: csharp - :copyable: - :dedent: - -.. literalinclude:: /includes/code-examples/Address.cs - :language: csharp - :copyable: - :dedent: - -.. literalinclude:: /includes/code-examples/GradeEntry.cs - :language: csharp - :copyable: - :dedent: - -.. include:: /includes/convention-pack-note.rst - -This collection is from the :atlas:`sample datasets ` provided -by Atlas. See the :ref:`` to learn how to create a free MongoDB cluster -and load this sample data. - -.. _csharp-update-operation: - -Update One Document -------------------- - -To update one or more fields in a MongoDB document, call the ``UpdateOne()`` or -``UpdateOneAsync()`` method. These methods accept the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``filter`` - - A *query filter* that specifies the document to update. You can use the - ``Builders`` class to create a query filter. For more information about - query filters, see the - :manual:`{+mdb-server+} manual `. - - **Data Type:** `FilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ - - * - ``update`` - - An instance of the ``UpdateDefinition`` class. This object specifies the kind of update - operation, the fields to update, and the new value for each field. For a complete - list of update operations, see - :manual:`Field Update Operators ` in the - {+mdb-server+} manual. - - **Data Type:** `UpdateDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinition-1.html>`__ - - * - ``options`` - - *Optional.* An instance of the ``UpdateOptions`` class that specifies the - configuration for the update operation. The default value is ``null``. - - **Data Type:** `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ - - * - ``cancellationToken`` - - *Optional.* A token that you can use to cancel the operation. - - **Data type**: `CancellationToken `__ - -The following code example demonstrates how to perform an update operation. The -code performs the following steps: - -.. tip:: Aggregation Pipelines in Update Operations - - If you are using MongoDB Version 4.2 or later, you can use aggregation - pipelines made up of a subset of aggregation stages in update operations. For - more information on the aggregation stages MongoDB supports in - aggregation pipelines used in update operations, see the tutorial about building - :manual:`updates with aggregation pipelines `. - -Update One Document -~~~~~~~~~~~~~~~~~~~ - -The following code shows how to use the asynchronous ``UpdateOneAsync()`` method -or the synchronous ``UpdateOne()`` method to update one document. - -.. tabs:: - - .. tab:: Asynchronous - :tabid: update-one-async - - .. code-block:: csharp - :copyable: true - - var result = await _restaurantsCollection.UpdateOneAsync(filter, update); - - .. tab:: Synchronous - :tabid: update-one-sync - - .. code-block:: csharp - :copyable: true - - var result = _restaurantsCollection.UpdateOne(filter, update); - -Update Many Documents -~~~~~~~~~~~~~~~~~~~~~ - -The following code shows how to use the asynchronous -``UpdateManyAsync()`` method or the synchronous ``UpdateMany()`` method to -update all matched documents. - -.. tabs:: - - .. tab:: Asynchronous - :tabid: update-many-async - - .. code-block:: csharp - :copyable: true - - var result = await _restaurantsCollection.UpdateManyAsync(filter, update); - - .. tab:: Synchronous - :tabid: update-many-sync - - .. code-block:: csharp - :copyable: true - - var result = _restaurantsCollection.UpdateMany(filter, update); - -.. tip:: - - Find runnable examples that use these methods under :ref:`Additional - Information `. - -Customize the Update Operation -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Both methods optionally accept an ``UpdateOptions`` object as an additional parameter, -which represents options you can use to configure the update operation. -If you don't specify any ``UpdateOptions`` properties, the driver does -not customize the update operation. - -The ``UpdateOptions`` type allows you to configure options with the -following properties: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Property - - Description - - * - ``ArrayFilters`` - - | Specifies which array elements to modify for an update operation on an array field. - See :manual:`the MongoDB server manual` - for more information. - - * - ``BypassDocumentValidation`` - - | Specifies whether the update operation bypasses document validation. This lets you - update documents that don't meet the schema validation requirements, if any - exist. See :manual:`the MongoDB server manual` - for more information on schema validation. - - * - ``Collation`` - - | Specifies the kind of language collation to use when sorting - results. See :manual:`the MongoDB server manual` - for more information on collation. - - * - ``Comment`` - - | Gets or sets the user-provided comment for the operation. - See :manual:`the MongoDB server manual` - for more information. - - * - ``Hint`` - - | Gets or sets the index to use to scan for documents. - See :manual:`the MongoDB server manual` - for more information. - - * - ``IsUpsert`` - - | Specifies whether the update operation performs an upsert operation if no - documents match the query filter. - See :manual:`the MongoDB server manual ` - for more information. - - * - ``Let`` - - | Gets or sets the let document. - See :manual:`the MongoDB server manual ` - for more information. - -Return Value -~~~~~~~~~~~~ - -The ``UpdateOne()`` and ``UpdateMany()`` methods each return an ``UpdateResult`` -object. The ``UpdateResult`` type contains the following properties: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Property - - Description - - * - ``IsAcknowledged`` - - | Indicates whether the update operation was acknowledged by MongoDB. - - * - ``IsModifiedCountAvailable`` - - | Indicates whether you can read the count of updated records on the - ``UpdateResult``. - - * - ``MatchedCount`` - - | The number of documents that matched the query filter, regardless of - how many were updated. - - * - ``ModifiedCount`` - - | The number of documents updated by the update operation. If an updated - document is identical to the original, it won't be included in this count. - - * - ``UpsertedId`` - - | The ID of the document that was upserted in the database, if the driver - performed an upsert. - -Example -~~~~~~~ - -The following code uses the ``UpdateMany()`` method to find all documents where the -``borough`` field has the value "Manhattan", then updates the ``borough`` -value in these documents to "Manhattan (north)". Because the ``IsUpsert`` option is -set to ``true``, the driver inserts a new document if the query filter doesn't -match any existing documents. - -.. io-code-block:: - :copyable: true - - .. input:: - :language: csharp - - var filter = Builders.Filter - .Eq(restaurant => restaurant.Borough, "Manhattan"); - - var update = Builders.Update - .Set(restaurant => restaurant.Borough, "Manhattan (north)"); - - UpdateOptions opts = new UpdateOptions() - { - Comment = new BsonString("Borough updated for C# Driver Fundamentals"), - IsUpsert = true - }; - - Console.WriteLine("Updating documents..."); - var result = _restaurantsCollection.UpdateMany(filter, update, opts); - - Console.WriteLine($"Updated documents: {result.ModifiedCount}"); - Console.WriteLine($"Result acknowledged? {result.IsAcknowledged}"); - - .. output:: - :language: none - :visible: false - - Updating documents... - Updated documents: 10259 - Result acknowledged? True - -.. note:: - - If the preceding example used the ``UpdateOne()`` method instead of - ``UpdateMany()``, the driver would update only the first of the - matched documents. - -.. _csharp-change-info: - -Additional Information ----------------------- - -For runnable examples of the update operations, see the following usage -examples: - -- :ref:`csharp-update-one` -- :ref:`csharp-update-many` - -To learn more about creating query filters, see the :ref:`csharp-specify-query` guide. - -API Documentation -~~~~~~~~~~~~~~~~~ - -To learn more about any of the methods or types discussed in this -guide, see the following API documentation: - -* `UpdateOne() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateOne.html>`__ -* `UpdateOneAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateOneAsync.html>`__ -* `UpdateMany() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateMany.html>`__ -* `UpdateManyAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateManyAsync.html>`__ -* `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ -* `UpdateResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateResult.html>`__ - -.. _csharp-update-instruqt-lab: - -.. instruqt:: /mongodb-docs/tracks/update-a-document---c-net-driver?token=em_69t_l-j0BC_en7Uy - :title: UpdateManyAsync() Lesson - :drawer: \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations/update/update-one.txt b/source/fundamentals/crud/write-operations/update/update-one.txt new file mode 100644 index 00000000..4943e724 --- /dev/null +++ b/source/fundamentals/crud/write-operations/update/update-one.txt @@ -0,0 +1,841 @@ +.. _csharp-update-one: + +================ +Update Documents +================ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: synchronous, asynchronous + +Overview +-------- + +In this guide, you can learn how to use the {+driver-long+} to update the +values of fields in MongoDB documents. + +The {+driver-short+} provides the following methods to update fields: + +- ``UpdateOne()`` or ``UpdateOneAsync()`` + +.. tip:: Interactive Lab + + This page includes a short interactive lab that demonstrates how to + modify data by using the ``UpdateManyAsync()`` method. You can complete this + lab directly in your browser window without installing MongoDB or a code editor. + + To start the lab, click the :guilabel:`Open Interactive Tutorial` button at the + top of the page. To expand the lab to a full-screen format, click the + full-screen button (:guilabel:`â›¶`) in the top-right corner of the lab pane. + +.. note:: Method Overloads + + Many of the methods in this guide have multiple overloads. The examples + in this guide use the simplest overload for demonstration purposes. For + more information about the available overloads, see the + :manual:`{+new-api-root+} API documentation `. + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``restaurants`` collection +from the ``sample_restaurants`` database. The documents in this +collection use the following ``Restaurant``, ``Address``, and ``GradeEntry`` +classes as models: + +.. literalinclude:: /includes/code-examples/Restaurant.cs + :language: csharp + :copyable: + :dedent: + +.. literalinclude:: /includes/code-examples/Address.cs + :language: csharp + :copyable: + :dedent: + +.. literalinclude:: /includes/code-examples/GradeEntry.cs + :language: csharp + :copyable: + :dedent: + +.. include:: /includes/convention-pack-note.rst + +This collection is from the :atlas:`sample datasets ` provided +by Atlas. See the :ref:`` to learn how to create a free MongoDB cluster +and load this sample data. + +.. _csharp-update-operation: + +Update Methods and Parameters +------------------------------ + +To update one or more fields in a MongoDB document, call the ``UpdateOne()`` or +``UpdateOneAsync()`` method. These methods accept the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``filter`` + - A *query filter* that specifies the document to update. You can use the + ``Builders`` class to create a query filter. For more information about + query filters, see the + :manual:`{+mdb-server+} manual `. + + **Data Type:** `FilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ + + * - ``update`` + - An instance of the ``UpdateDefinition`` class. This object specifies the kind of update + operation, the fields to update, and the new value for each field. You can use the + ``Builders`` class to create an ``UpdateDefinition`` object. + + **Data Type:** `UpdateDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinition-1.html>`__ + + * - ``options`` + - *Optional.* An instance of the ``UpdateOptions`` class that specifies the + configuration for the update operation. The default value is ``null``. + + **Data Type:** `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ + + * - ``cancellationToken`` + - *Optional.* A token that you can use to cancel the operation. + + **Data type**: `CancellationToken `__ + +.. To update one or more documents in a MongoDB collection, perform the following steps: + +.. 1. Create a query filter that specifies the documents to update. Link out to the query filter page. +.. #. Create an update definition that specifies the fields to update and the new values. Covered later. +.. #. Call the ``UpdateOne()`` or ``UpdateOneAsync()`` method to update the document. + +The following sections describe how to create update definitions for different operations. + +Single Values +------------- + +The {+driver-short+} supports the field update operators described in the +:manual:`{+mdb-server+} manual `. To specify an +update operation, call the corresponding method from the ``Builders.Update`` property. +The following sections describe these methods in more detail. + +Increment a Value +~~~~~~~~~~~~~~~~~ + +To increment the value of a field by a specific amount, call the ``Builders.Update.Inc()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to increment. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The amount to increment the field by. + + **Data Type:** ``TField`` + +Set If Lower or Greater +~~~~~~~~~~~~~~~~~~~~~~~ + +To update the value of the field to a specified value, *but only if the specified value +is greater than the current value of the field,* call the ``Builders.Update.Max()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The value to set the field to. + + **Data Type:** ``TField`` + +To update the value of the field to a specified value, *but only if the specified value +is lesser than the current value of the field,* call the ``Builders.Update.Min()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The value to set the field to. + + **Data Type:** ``TField`` + +Multiply a Value +~~~~~~~~~~~~~~~~ + +To multiply the value of a field by a specific amount, call the ``Builders.Update.Mul()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The amount to multiply the field by. + + **Data Type:** ``TField`` + +Rename a Field +~~~~~~~~~~~~~~ + +To rename a field, call the ``Builders.Update.Rename()`` method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to rename. + + **Data Type:** ``Expression>`` + + * - ``newName`` + - The new name for the field. + + **Data Type:** ``string`` + +Set a Value +~~~~~~~~~~~ + +To set the value of a field to a specific value, call the ``Builders.Update.Set()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The value to set the field to. + + **Data Type:** ``TField`` + +Unset a Field +~~~~~~~~~~~~~ + +To remove a field from a document, call the ``Builders.Update.Unset()`` method. This method accepts the following parameter: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to remove. + + **Data Type:** ``Expression>`` + +Set on Insert +~~~~~~~~~~~~~ + +To set the value of a field only if the document is an upsert, call the ``Builders.Update.SetOnInsert()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The value to set the field to. + + **Data Type:** ``TField`` + +Set the Current Date +~~~~~~~~~~~~~~~~~~~~ + +To set the value of a field to the current date and time, call the ``Builders.Update.CurrentDate()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``type`` + - The format of the date and time, defined in the ``UpdateDefinitionCurrentDateType`` + enum. The default value is ``null``. + + **Data Type:** `UpdateDefinitionCurrentDateType? <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionCurrentDateType.html>`__ + +The following code example performs these steps: + +1. Creates a query filter that matches documents where the value of the ``name`` field + is "Bagels N Buns". +#. Creates an update definition that sets the value of the ``name`` field to "2 Bagels 2 Buns". +#. Calls the ``UpdateOne()`` method to update the document. + +Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding +code. + +.. tabs:: + + .. tab:: Synchronous + :tabid: update-one-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one + :end-before: // end-update-one + + .. tab:: Asynchronous + :tabid: update-one-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneAsync.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-async + :end-before: // end-update-one-async + +.. tip:: Aggregation Pipelines in Update Operations + + If you are using MongoDB Version 4.2 or later, you can use aggregation + pipelines made up of a subset of aggregation stages in update operations. For + more information on the aggregation stages MongoDB supports in + aggregation pipelines used in update operations, see the tutorial about building + :manual:`updates with aggregation pipelines `. + +Arrays +------ + +The {+driver-short+} supports the array update operators and modifiers described in the +:manual:`{+mdb-server+} manual `. +To specify an update operation, call the corresponding method from the ``Builders.Update`` +property. The following sections describe these methods in more detail. + +Add One Value +~~~~~~~~~~~~~ + +To add one value to the end of an array, call the ``Builders.Update.Push()`` method. +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``value`` + - The value to add to the end of the array field. + + **Data Type:** ``TItem`` + +The following code example pushes a new ``GradeEntry`` object into the ``Grades`` +array in the matching document. Select the :guilabel:`Synchronous` or +:guilabel:`Asynchronous` tab to see the corresponding code. + +.. tabs:: + + .. tab:: Synchronous + :tabid: update-one-array-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-array + :end-before: // end-update-one-array + + .. tab:: Asynchronous + :tabid: update-one-array-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-array-async + :end-before: // end-update-one-array-async + +To add one value to the end of an array, *but only if it doesn't already exist in the array*, +call the ``Builders.Update.AddToSet()`` method. +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``value`` + - The value to add to the end of the array field. + + **Data Type:** ``TItem`` + +The following code example pushes a new ``GradeEntry`` object into the ``Grades`` +array in the matching document. Select the :guilabel:`Synchronous` or +:guilabel:`Asynchronous` tab to see the corresponding code. + +.. tip:: Specify a Position + + To add a value at a specific position in an array, call the ``PushEach()`` method. + +Add Multiple Values +~~~~~~~~~~~~~~~~~~~ + +To add multiple values to an array, call the ``Builders.Update.PushEach()`` method. +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``values`` + - The values to add to the array field. + + **Data Type:** ``IEnumerable`` + + * - ``slice`` + - The number of elements to keep in the array. If the value is negative, the + method keeps the specified number of elements from the end of the array. + + **Data Type:** ``int?`` + + * - ``position`` + - The position in the array at which to add the values. + + **Data Type:** ``int?`` + + * - ``sort`` + - The values to add to the array field. + + **Data Type:** `SortDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.SortDefinition-1.html>`__ + +To add multiple values to an array only if they aren't there, call the +``Builders.Update.AddToSetEach()`` method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``values`` + - The values to add to the array field. + + **Data Type:** ``IEnumerable`` + +Remove Values +~~~~~~~~~~~~~ + +To remove the first value from an array, call the ``Builders.Update.PopFirst()`` method. +This method accepts the following parameter: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to remove the first value from. + + **Data Type:** ``Expression>>`` + +To remove the last value from an array, call the ``Builders.Update.PopLast()`` method: +This method accepts the following parameter: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to remove the last value from. + + **Data Type:** ``Expression>>`` + +To remove all instances of a specific value from an array, call the ``Builders.Update.Pull()`` method: +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``value`` + - The value to remove from the array field. + + **Data Type:** ``IEnumerable`` + +To remove all instances of more than one specific value from an array, call the ``Builders.Update.PullAll()`` method: +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``values`` + - The values to remove from the array field. + + **Data Type:** ``IEnumerable`` + +To remove all values that match a specific condition from an array, call the ``Builders.Update.PullFilter()`` method: +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``filter`` + - A query filter that specifies the condition for values to remove. + + **Data Type:** `FilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ + +Update Matching Elements +~~~~~~~~~~~~~~~~~~~~~~~~ + +To query and update specific elements in an array field, use +the :manual:`positional operator ` (``$``) +when you specify the field to update. +Combined with the ``Builders.Update.Set()`` method, you can use this operator to query +and update specific elements in an array field. + +To update the first array element that matches your query filter, use the +positional ``$`` operator. The array value must appear be part of the query filter. + +The following code example queries the ``restaurants`` collection for a document +that contains a grade of 2. It then updates that grade to 22 in the matching documents. +Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding code. + +To update all array elements in the matching documents, use the all positional operator +(``$[]``). + +The following code example queries the ``restaurants`` collection for a document +where the ``name`` is ``"Downtown Deli"``. It then updates all that grade to 22 in the matching documents. +Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding code. + +To update all array elements that match your query filter, use the all positional operator +(``$[]``). The array value must appear be part of the query filter. + +The following code example queries the ``restaurants`` collection for a document +that contains a grade of 2. It then updates that grade to 22 in the matching documents. + +Customize the Update Operation +------------------------------ + +The preceding update methods optionally accept an ``UpdateOptions`` object as an additional +parameter. You can use this argument to configure the update operation. + +The ``UpdateOptions`` class contains the following properties: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Property + - Description + + * - ``ArrayFilters`` + - Specifies which array elements to modify for an update operation on an array field. + See :manual:`the MongoDB server manual` + for more information. + + **Data Type:** IEnumerable<`ArrayFilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.ArrayFilterDefinition.html>`__> + + * - ``BypassDocumentValidation`` + - Specifies whether the update operation bypasses document validation. This lets you + update documents that don't meet the schema validation requirements, if any + exist. See :manual:`the MongoDB server manual` + for more information on schema validation. + + **Data Type:** ``bool?`` + + * - ``Collation`` + - Specifies the kind of language collation to use when sorting + results. See :manual:`the MongoDB server manual` + for more information on collation. + + **Data Type:** `Collation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Collation.html>`__ + + * - ``Comment`` + - Gets or sets the user-provided comment for the operation. + See :manual:`the MongoDB server manual` + for more information. + + **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ + + * - ``Hint`` + - Gets or sets the index to use to scan for documents. + See :manual:`the MongoDB server manual` + for more information. + + **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ + + * - ``IsUpsert`` + - Specifies whether the update operation performs an upsert operation if no + documents match the query filter. + See :manual:`the MongoDB server manual ` + for more information. + + **Data Type:** ``bool`` + + * - ``Let`` + - Gets or sets the let document. + See :manual:`the MongoDB server manual ` + for more information. + + **Data Type:** `BsonDocument <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonDocument.html>`__ + +Return Value +------------ + +The ``UpdateOne()`` and ``UpdateMany()`` methods return an ``UpdateResult`` +object. The ``UpdateOneAsync()`` and ``UpdateManyAsync()`` methods return an asynchronous +version of this type, a ``Task`` object. +The ``UpdateResult`` class contains the following properties: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Property + - Description + + * - ``IsAcknowledged`` + - Indicates whether the replace operation was acknowledged by MongoDB. + + **Data Type:** ``bool`` + + * - ``IsModifiedCountAvailable`` + - Indicates whether you can read the count of replaced records on the + ``ReplaceOneResult``. + + **Data Type:** ``bool`` + + * - ``MatchedCount`` + - The number of documents that matched the query filter, regardless of + whether one was replaced. + + **Data Type:** ``long`` + + * - ``ModifiedCount`` + - The number of documents replaced by the replace operation. + + **Data Type:** ``long`` + + * - ``UpsertedId`` + - The ID of the document that was upserted in the database, if the driver + performed an upsert. + + **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ + +Example +------- + +The following code uses the ``UpdateMany()`` method to find all documents where the +``borough`` field has the value "Manhattan", then updates the ``borough`` +value in these documents to "Manhattan (north)". Because the ``IsUpsert`` option is +set to ``true``, the driver inserts a new document if the query filter doesn't +match any existing documents. + +.. io-code-block:: + :copyable: true + + .. input:: + :language: csharp + + var filter = Builders.Filter + .Eq(restaurant => restaurant.Borough, "Manhattan"); + + var update = Builders.Update + .Set(restaurant => restaurant.Borough, "Manhattan (north)"); + + UpdateOptions opts = new UpdateOptions() + { + Comment = new BsonString("Borough updated for C# Driver Fundamentals"), + IsUpsert = true + }; + + Console.WriteLine("Updating documents..."); + var result = _restaurantsCollection.UpdateMany(filter, update, opts); + + Console.WriteLine($"Updated documents: {result.ModifiedCount}"); + Console.WriteLine($"Result acknowledged? {result.IsAcknowledged}"); + + .. output:: + :language: none + :visible: false + + Updating documents... + Updated documents: 10259 + Result acknowledged? True + +Multiple Updates +---------------- + +To combine multiple update definitions into one, call the ``Builders.Update.Combine()`` method. +This method accepts the following parameter: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``updates`` + - An array of update definitions to combine. + + **Data Type:** ``UpdateDefinition[]`` + +This method returns a single ``UpdateDefinition`` object, which you can then pass to the +``UpdateOne()`` or ``UpdateMany()`` method. + +.. _csharp-change-info: + +Additional Information +---------------------- + +For runnable examples of the update operations, see the following usage +examples: + +- :ref:`csharp-update-one` +- :ref:`csharp-update-many` + +To learn more about creating query filters, see the :ref:`csharp-specify-query` guide. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +* `UpdateOne() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateOne.html>`__ +* `UpdateOneAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateOneAsync.html>`__ +* `UpdateMany() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateMany.html>`__ +* `UpdateManyAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateManyAsync.html>`__ +* `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ +* `UpdateResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateResult.html>`__ + +.. _csharp-update-instruqt-lab: + +.. instruqt:: /mongodb-docs/tracks/update-a-document---c-net-driver?token=em_69t_l-j0BC_en7Uy + :title: UpdateManyAsync() Lesson + :drawer: \ No newline at end of file diff --git a/source/includes/code-examples/update-one/UpdateOne.cs b/source/includes/code-examples/update-one/UpdateOne.cs index 1c1ded85..30dacbd3 100644 --- a/source/includes/code-examples/update-one/UpdateOne.cs +++ b/source/includes/code-examples/update-one/UpdateOne.cs @@ -14,7 +14,8 @@ public class UpdateOne public static void Main(string[] args) { - try { + try + { Setup(); // Prints extra space for console readability @@ -25,8 +26,10 @@ public static void Main(string[] args) Console.WriteLine($"Updated documents: {syncResult.ModifiedCount}"); ResetSampleData(); - // Prints a message if any exceptions occur during the operation - } catch (MongoException me) { + // Prints a message if any exceptions occur during the operation + } + catch (MongoException me) + { Console.WriteLine("Unable to update due to an error: " + me); } } @@ -34,23 +37,60 @@ public static void Main(string[] args) private static UpdateResult UpdateOneRestaurant() { // start-update-one - const string oldValue = "Bagels N Buns"; - const string newValue = "2 Bagels 2 Buns"; - // Creates a filter for all documents with a "name" of "Bagels N Buns" var filter = Builders.Filter - .Eq(restaurant => restaurant.Name, oldValue); + .Eq(restaurant => restaurant.Name, "Bagels N Buns"); // Creates instructions to update the "name" field of the first document // that matches the filter var update = Builders.Update - .Set(restaurant => restaurant.Name, newValue); + .Set(restaurant => restaurant.Name, "2 Bagels 2 Buns"); // Updates the first document that has a "name" value of "Bagels N Buns" return _restaurantsCollection.UpdateOne(filter, update); // end-update-one } + public static UpdateResult UpdateOneRestaurantArray() + { + // start-update-one-array + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var update = Builders.Update + .Push(restaurant => restaurant.Grades, new GradeEntry() + { + Date = DateTime.Now, + Grade = "A", + Score = 96 + }); + + var result = _restaurantsCollection.UpdateOne(filter, update); + + return result; + // end-update-one-array + } + + public static async Task UpdateOneRestaurantArrayAsync() + { + // start-update-one-array-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var update = Builders.Update + .Push(restaurant => restaurant.Grades, new GradeEntry() + { + Date = DateTime.Now, + Grade = "A", + Score = 96 + }); + + var result = await _restaurantsCollection.UpdateOneAsync(filter, update); + + return result; + // end-update-one-array-async + } + private static void Setup() { // Allows automapping of the camelCase database fields to models diff --git a/source/includes/code-examples/update-one/UpdateOneAsync.cs b/source/includes/code-examples/update-one/UpdateOneAsync.cs index 166174dc..f4dfe72b 100644 --- a/source/includes/code-examples/update-one/UpdateOneAsync.cs +++ b/source/includes/code-examples/update-one/UpdateOneAsync.cs @@ -14,7 +14,8 @@ public class UpdateOneAsync public static async Task Main(string[] args) { - try { + try + { Setup(); // Prints extra space for console readability @@ -25,8 +26,10 @@ public static async Task Main(string[] args) Console.WriteLine($"Updated documents: {asyncResult.ModifiedCount}"); ResetSampleData(); - // Prints a message if any exceptions occur during the operation - } catch (MongoException e) { + // Prints a message if any exceptions occur during the operation + } + catch (MongoException e) + { Console.WriteLine("Unable to update due to an error: " + me); } } @@ -34,17 +37,14 @@ public static async Task Main(string[] args) private static async Task UpdateOneRestaurantAsync() { // start-update-one-async - const string oldValue = "Bagels N Buns"; - const string newValue = "2 Bagels 2 Buns"; - // Creates a filter for all documents with a "name" of "Bagels N Buns" var filter = Builders.Filter - .Eq(restaurant => restaurant.Name, oldValue); + .Eq(restaurant => restaurant.Name, "Bagels N Buns"); // Creates instructions to update the "name" field of the first document // that matches the filter var update = Builders.Update - .Set(restaurant => restaurant.Name, newValue); + .Set(restaurant => restaurant.Name, "2 Bagels 2 Buns"); // Updates the first document that has a "name" value of "Bagels N Buns" return await _restaurantsCollection.UpdateOneAsync(filter, update); From b44cdfc6b62c5c0fad0016d47fb83f18b418fb90 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Wed, 20 Nov 2024 15:41:29 -0600 Subject: [PATCH 05/39] wip --- .../crud/write-operations/update.txt | 356 +++++++- .../crud/write-operations/update/arrays.txt | 366 ++++++-- .../crud/write-operations/update/fields.txt | 317 +++++++ .../write-operations/update/update-one.txt | 841 ------------------ .../code-examples/update-many/UpdateMany.cs | 40 +- .../code-examples/update-one/UpdateOne.cs | 30 + 6 files changed, 1025 insertions(+), 925 deletions(-) create mode 100644 source/fundamentals/crud/write-operations/update/fields.txt delete mode 100644 source/fundamentals/crud/write-operations/update/update-one.txt diff --git a/source/fundamentals/crud/write-operations/update.txt b/source/fundamentals/crud/write-operations/update.txt index 9a99db52..b0acbb49 100644 --- a/source/fundamentals/crud/write-operations/update.txt +++ b/source/fundamentals/crud/write-operations/update.txt @@ -16,7 +16,7 @@ Update Documents :values: reference .. meta:: - :keywords: update, synchronous, asynchronous, bulk + :keywords: synchronous, asynchronous .. toctree:: :caption: Update Documents @@ -26,3 +26,357 @@ Update Documents Overview -------- + +In this guide, you can learn how to use the {+driver-long+} to update +values in MongoDB documents. + +The {+driver-short+} provides the following methods to update values: + +- ``UpdateOne()``: Updates one or more fields in a single document. +- ``UpdateOneAsync()``: The asynchronous version of ``UpdateOne()``. +- ``UpdateMany()``: Updates one or more fields in multiple documents. +- ``UpdateManyAsync()``: The asynchronous version of ``UpdateMany()``. + +The following sections describe these methods in more detail. + +.. note:: Method Overloads + + Many of the methods in this guide have multiple overloads. The examples + in this guide use the simplest overload for demonstration purposes. For + more information about the available overloads, see the + :manual:`{+new-api-root+} API documentation `. + +.. tip:: Interactive Lab + + This page includes a short interactive lab that demonstrates how to + modify data by using the ``UpdateManyAsync()`` method. You can complete this + lab directly in your browser window without installing MongoDB or a code editor. + + To start the lab, click the :guilabel:`Open Interactive Tutorial` button at the + top of the page. To expand the lab to a full-screen format, click the + full-screen button (:guilabel:`â›¶`) in the top-right corner of the lab pane. + +Methods and Parameters +---------------------- + +The ``UpdateOne()``, ``UpdateOneAsync()``, ``UpdateMany()``, and ``UpdateManyAsync()`` +methods all accept the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``filter`` + - An instance of the ``FilterDefinition`` class that specifies the documents to update. + To learn how to create a query filter, see :ref:`csharp-specify-query`. + + **Data Type:** `FilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ + + * - ``update`` + - An instance of the ``UpdateDefinition`` class. This object specifies the kind of update + operation, the fields to update, and the new value for each field. To learn how to + create an ``UpdateDefinition`` object, + see :ref:`csharp-update-fields` and :ref:`csharp-update-arrays`. + + **Data Type:** `UpdateDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinition-1.html>`__ + + * - ``options`` + - *Optional.* An instance of the ``UpdateOptions`` class that specifies the + configuration for the update operation. The default value is ``null``. To learn + about the available options, see :ref:`csharp-update-options`. + + **Data Type:** `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ + + * - ``cancellationToken`` + - *Optional.* A token that you can use to cancel the operation. + + **Data type**: `CancellationToken `__ + +Update Multiple Values +---------------------- + +The ``UpdateOne()``, ``UpdateOneAsync()``, ``UpdateMany()``, and ``UpdateManyAsync()`` +methods each accept one ``UpdateDefinition`` object. The following sections describe how +to multiple values in a single method call. + +Combine Update Definitions +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The ``Builders.Update.Combine()`` method lets you combine multiple ``UpdateDefinition`` +objects. This method accepts the following parameter: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``updates`` + - An array of update definitions to combine. + + **Data Type:** ``UpdateDefinition[]`` + +The ``Combine()`` method returns a single ``UpdateDefinition`` object that defines +multiple update operations. + +The following code example uses the ``Combine()`` method to combine a +:manual:`$set ` operation and a +:manual:`$pop ` +operation: + +.. tabs:: + + .. tab:: UpdateOne (Synchronous) + :tabid: update-one-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-combine-sync + :end-before: // end-combine-sync + + .. tab:: UpdateOne (Asynchronous) + :tabid: update-one-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-combine-async + :end-before: // end-combine-async + + .. tab:: UpdateMany (Synchronous) + :tabid: update-many-sync + + .. literalinclude:: /includes/code-examples/update-many/UpdateMany.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-combine-sync + :end-before: // end-combine-sync + + .. tab:: UpdateMany (Asynchronous) + :tabid: update-many-async + + .. literalinclude:: /includes/code-examples/update-many/UpdateMany.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-combine-async + :end-before: // end-combine-async + +Update Pipelines +~~~~~~~~~~~~~~~~ + +Builders.Update.Pipeline is used to create an update pipeline for MongoDB update operations. An update pipeline allows you to specify a sequence of update stages that modify the documents in a collection. Each stage in the pipeline is an update operation that transforms the document in some way. This is similar to the aggregation pipeline but is used specifically for updates. +This method accepts the following parameter: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``pipeline`` + - A ``PipelineDefinition`` instance that specifies the update pipeline. + + **Data Type:** ``PipelineDefinition`` + +.. tip:: Aggregation Pipelines in Update Operations + + If you are using MongoDB Version 4.2 or later, you can use aggregation + pipelines made up of a subset of aggregation stages in update operations. For + more information on the aggregation stages MongoDB supports in + aggregation pipelines used in update operations, see the tutorial about building + :manual:`updates with aggregation pipelines `. + +.. _csharp-update-options: + +Customize the Update Operation +------------------------------ + +To combine multiple update definitions into one, call the ``Builders.Update.Combine()`` method. +This method accepts the following parameter: + +The preceding update methods optionally accept an ``UpdateOptions`` object as an additional +parameter. You can use this argument to configure the update operation. + +The ``UpdateOptions`` class contains the following properties: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Property + - Description + + * - ``ArrayFilters`` + - Specifies which array elements to modify for an update operation on an array field. + See :manual:`the MongoDB server manual` + for more information. + + **Data Type:** IEnumerable<`ArrayFilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.ArrayFilterDefinition.html>`__> + + * - ``BypassDocumentValidation`` + - Specifies whether the update operation bypasses document validation. This lets you + update documents that don't meet the schema validation requirements, if any + exist. See :manual:`the MongoDB server manual` + for more information on schema validation. + + **Data Type:** ``bool?`` + + * - ``Collation`` + - Specifies the kind of language collation to use when sorting + results. See :manual:`the MongoDB server manual` + for more information on collation. + + **Data Type:** `Collation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Collation.html>`__ + + * - ``Comment`` + - Gets or sets the user-provided comment for the operation. + See :manual:`the MongoDB server manual` + for more information. + + **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ + + * - ``Hint`` + - Gets or sets the index to use to scan for documents. + See :manual:`the MongoDB server manual` + for more information. + + **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ + + * - ``IsUpsert`` + - Specifies whether the update operation performs an upsert operation if no + documents match the query filter. + See :manual:`the MongoDB server manual ` + for more information. + + **Data Type:** ``bool`` + + * - ``Let`` + - Gets or sets the let document. + See :manual:`the MongoDB server manual ` + for more information. + + **Data Type:** `BsonDocument <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonDocument.html>`__ + +Example +~~~~~~~ + +The following code uses the ``UpdateMany()`` method to find all documents where the +``borough`` field has the value "Manhattan", then updates the ``borough`` +value in these documents to "Manhattan (north)". Because the ``IsUpsert`` option is +set to ``true``, the driver inserts a new document if the query filter doesn't +match any existing documents. + +.. io-code-block:: + :copyable: true + + .. input:: + :language: csharp + + var filter = Builders.Filter + .Eq(restaurant => restaurant.Borough, "Manhattan"); + + var update = Builders.Update + .Set(restaurant => restaurant.Borough, "Manhattan (north)"); + + UpdateOptions opts = new UpdateOptions() + { + Comment = new BsonString("Borough updated for C# Driver Fundamentals"), + IsUpsert = true + }; + + Console.WriteLine("Updating documents..."); + var result = _restaurantsCollection.UpdateMany(filter, update, opts); + + Console.WriteLine($"Updated documents: {result.ModifiedCount}"); + Console.WriteLine($"Result acknowledged? {result.IsAcknowledged}"); + + .. output:: + :language: none + :visible: false + + Updating documents... + Updated documents: 10259 + Result acknowledged? True + +Return Value +------------ + +The ``UpdateOne()`` and ``UpdateMany()`` methods return an ``UpdateResult`` +object. The ``UpdateOneAsync()`` and ``UpdateManyAsync()`` methods return an asynchronous +version of this type, a ``Task`` object. +The ``UpdateResult`` class contains the following properties: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Property + - Description + + * - ``IsAcknowledged`` + - Indicates whether the replace operation was acknowledged by MongoDB. + + **Data Type:** ``bool`` + + * - ``IsModifiedCountAvailable`` + - Indicates whether you can read the count of replaced records on the + ``ReplaceOneResult``. + + **Data Type:** ``bool`` + + * - ``MatchedCount`` + - The number of documents that matched the query filter, regardless of + whether one was replaced. + + **Data Type:** ``long`` + + * - ``ModifiedCount`` + - The number of documents replaced by the replace operation. + + **Data Type:** ``long`` + + * - ``UpsertedId`` + - The ID of the document that was upserted in the database, if the driver + performed an upsert. + + **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ + +Additional Information +---------------------- + +For runnable examples of the update operations, see the following usage +examples: + +- :ref:`csharp-update-one` +- :ref:`csharp-update-many` + +To learn more about creating query filters, see the :ref:`csharp-specify-query` guide. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +* `UpdateOne() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateOne.html>`__ +* `UpdateOneAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateOneAsync.html>`__ +* `UpdateMany() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateMany.html>`__ +* `UpdateManyAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateManyAsync.html>`__ +* `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ +* `UpdateResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateResult.html>`__ + +.. _csharp-update-instruqt-lab: + +.. instruqt:: /mongodb-docs/tracks/update-a-document---c-net-driver?token=em_69t_l-j0BC_en7Uy + :title: UpdateManyAsync() Lesson + :drawer: \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations/update/arrays.txt b/source/fundamentals/crud/write-operations/update/arrays.txt index 4c5ef23a..bffb2f8e 100644 --- a/source/fundamentals/crud/write-operations/update/arrays.txt +++ b/source/fundamentals/crud/write-operations/update/arrays.txt @@ -1,126 +1,334 @@ -Specifying Array Elements -------------------------- +.. _csharp-update-arrays: -You can specify which array elements to update using a positional -operator. Positional operators can specify the first, all, or certain -array elements to update. +============= +Update Arrays +============= -To specify elements in an array with positional operators, use **dot -notation**. Dot notation is a property access syntax for navigating BSON -objects. +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol -For additional information, see the Server Manual Entry on -:manual:`dot notation `. +.. facet:: + :name: genre + :values: reference -The First Matching Array Element -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. meta:: + :keywords: synchronous, asynchronous -Example -``````` +Overview +-------- -The following example performs these actions: +On this page, you can learn how to use the {+driver-long+} to update array +fields in MongoDB documents. This page describes how to create ``UpdateDefinition`` +objects that specify the update operations you want to perform on array fields. +You can pass these objects to the update methods described on *this page.* -- Query for a document with a ``qty`` field containing the value "18" -- Decrement the first array value in the document that matches the query filter by "3" +The {+driver-short+} supports the array update operators and modifiers described in the +:manual:`{+mdb-server+} manual `. +To specify an update operation, call the corresponding method from the ``Builders.Update`` +property. The following sections describe these methods in more detail. -.. literalinclude:: /includes/fundamentals/code-snippets/UpdateArray.java - :language: java +.. note:: Method Overloads + + Many of the methods on this page have multiple overloads. The examples + in this guide show only one overload for each method. For + more information about the available overloads, see the + :manual:`{+new-api-root+} API documentation `. + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``restaurants`` collection +from the ``sample_restaurants`` database. The documents in this +collection use the following ``Restaurant``, ``Address``, and ``GradeEntry`` +classes as models: + +.. literalinclude:: /includes/code-examples/Restaurant.cs + :language: csharp + :copyable: + :dedent: + +.. literalinclude:: /includes/code-examples/Address.cs + :language: csharp + :copyable: :dedent: - :start-after: begin updateValueExample - :end-before: end updateValueExample -The preceding example updates the original document to the following state: +.. literalinclude:: /includes/code-examples/GradeEntry.cs + :language: csharp + :copyable: + :dedent: + +.. include:: /includes/convention-pack-note.rst -.. code-block:: json - :copyable: false +This collection is from the :atlas:`sample datasets ` provided +by Atlas. See the :ref:`` to learn how to create a free MongoDB cluster +and load this sample data. - { "_id": 1, "color": "green", "qty": [8, 12, 15] } +Add One Value +------------- -For more information about the methods and operators mentioned in this section, -see the following resources: +To add one value to the end of an array, call the ``Builders.Update.Push()`` method. +This method accepts the following parameters: -- :manual:`Positional $ Operator ` Server Manual Entry -- `inc() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#inc(java.lang.String,java.lang.Number)>`__ API Documentation +.. list-table:: + :widths: 30 70 + :header-rows: 1 -Matching All Array Elements -~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * - Parameter + - Description -To update all elements in an array, use the all positional ``$[]`` operator. + * - ``field`` + - An expression that specifies the array field to add a value to. -Example -``````` + **Data Type:** ``Expression>>`` -The following example performs these actions: + * - ``value`` + - The value to add to the end of the array field. -- Query for the sample document -- Multiply array elements matching the query filter by "2" + **Data Type:** ``TItem`` -.. literalinclude:: /includes/fundamentals/code-snippets/UpdateArray.java - :language: java - :dedent: - :start-after: begin updateAllElementsExample - :end-before: end updateAllElementsExample +The following code example pushes a new ``GradeEntry`` object into the ``Grades`` +array in the matching document. Select the :guilabel:`Synchronous` or +:guilabel:`Asynchronous` tab to see the corresponding code. -The preceding example updates the original document to the following state: +.. tabs:: -.. code-block:: json - :copyable: false + .. tab:: Synchronous + :tabid: update-one-array-sync - { "_id": 1, "color": "green", "qty": [16, 24, 36] } + .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-array + :end-before: // end-update-one-array -For more information about the methods and operators mentioned in this section, -see the following resources: + .. tab:: Asynchronous + :tabid: update-one-array-async -- :manual:`All Positional $[] Operator ` Server Manual Entry -- `mul() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#mul(java.lang.String,java.lang.Number)>`__ API Documentation + .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-array-async + :end-before: // end-update-one-array-async -Matching Multiple Array Elements -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +To add one value to the end of an array, *but only if it doesn't already exist in the array*, +call the ``Builders.Update.AddToSet()`` method. +This method accepts the following parameters: -To update array elements that match a filter, use the -filtered positional ``$[]`` operator. You must include an -array filter in your update operation to specify which array elements to -update. +.. list-table:: + :widths: 30 70 + :header-rows: 1 -The ```` is the name you give your array filter. This value -must begin with a lowercase letter and contain only alphanumeric -characters. + * - Parameter + - Description -Example -``````` + * - ``field`` + - An expression that specifies the array field to add to. -The following example performs these actions: + **Data Type:** ``Expression>>`` -- Query for the sample document -- Set an array filter to search for values less than "15" -- Increment array elements matching the query filter by "5" + * - ``value`` + - The value to add to the end of the array field. -.. literalinclude:: /includes/fundamentals/code-snippets/UpdateArray.java - :language: java - :dedent: - :start-after: begin updateValueOptionsExample - :end-before: end updateValueOptionsExample + **Data Type:** ``TItem`` + +The following code example pushes a new ``GradeEntry`` object into the ``Grades`` +array in the matching document. Select the :guilabel:`Synchronous` or +:guilabel:`Asynchronous` tab to see the corresponding code. + +.. tip:: Specify a Position + + To add a value at a specific position in an array, call the ``PushEach()`` method. + +Add Multiple Values +------------------- + +To add multiple values to an array, call the ``Builders.Update.PushEach()`` method. +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``values`` + - The values to add to the array field. + + **Data Type:** ``IEnumerable`` + + * - ``slice`` + - The number of elements to keep in the array. If the value is negative, the + method keeps the specified number of elements from the end of the array. + + **Data Type:** ``int?`` + + * - ``position`` + - The position in the array at which to add the values. + + **Data Type:** ``int?`` + + * - ``sort`` + - The values to add to the array field. + + **Data Type:** `SortDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.SortDefinition-1.html>`__ + +To add multiple values to an array only if they aren't there, call the +``Builders.Update.AddToSetEach()`` method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``values`` + - The values to add to the array field. + + **Data Type:** ``IEnumerable`` + +Remove Values +------------- + +To remove the first value from an array, call the ``Builders.Update.PopFirst()`` method. +This method accepts the following parameter: -The preceding example updates the original document to the following state: +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to remove the first value from. + + **Data Type:** ``Expression>>`` + +To remove the last value from an array, call the ``Builders.Update.PopLast()`` method: +This method accepts the following parameter: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description -.. code-block:: json - :copyable: false + * - ``field`` + - An expression that specifies the array field to remove the last value from. - { "_id": 1, "color": "green", "qty": [13, 17, 18] } + **Data Type:** ``Expression>>`` -For more information about the methods and operators mentioned in this section, -see the following resources: +To remove all instances of a specific value from an array, call the ``Builders.Update.Pull()`` method: +This method accepts the following parameters: -- :manual:`Filtered Positional $[\] Operator ` Server Manual Entry -- `inc() <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html#inc(java.lang.String,java.lang.Number)>`__ API Documentation +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + * - ``value`` + - The value to remove from the array field. + + **Data Type:** ``IEnumerable`` + +To remove all instances of more than one specific value from an array, call the ``Builders.Update.PullAll()`` method: +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``values`` + - The values to remove from the array field. + + **Data Type:** ``IEnumerable`` + +To remove all values that match a specific condition from an array, call the ``Builders.Update.PullFilter()`` method: +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``filter`` + - A query filter that specifies the condition for values to remove. + + **Data Type:** `FilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ + +Update Matching Elements +------------------------ + +To query and update specific elements in an array field, use +the :manual:`positional operator ` (``$``) +when you specify the field to update. +Combined with the ``Builders.Update.Set()`` method, you can use this operator to query +and update specific elements in an array field. + +To update the first array element that matches your query filter, use the +positional ``$`` operator. The array value must appear be part of the query filter. + +The following code example queries the ``restaurants`` collection for a document +that contains a grade of 2. It then updates that grade to 22 in the matching documents. +Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding code. + +To update all array elements in the matching documents, use the all positional operator +(``$[]``). + +The following code example queries the ``restaurants`` collection for a document +where the ``name`` is ``"Downtown Deli"``. It then updates all that grade to 22 in the matching documents. +Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding code. + +To update all array elements that match your query filter, use the all positional operator +(``$[]``). The array value must appear be part of the query filter. + +The following code example queries the ``restaurants`` collection for a document +that contains a grade of 2. It then updates that grade to 22 in the matching documents. Updating Documents with LINQ3 ----------------------------- - LINQ syntax contains a positional operator (``$``) that you can use to update elements in an array field. Previous versions of the {+driver-short+} supported both the LINQ2 and LINQ3 providers. In LINQ2, you could use ``-1`` to indicate use of the positional operator. diff --git a/source/fundamentals/crud/write-operations/update/fields.txt b/source/fundamentals/crud/write-operations/update/fields.txt new file mode 100644 index 00000000..8d29610c --- /dev/null +++ b/source/fundamentals/crud/write-operations/update/fields.txt @@ -0,0 +1,317 @@ +.. _csharp-update-fields: + +============= +Update Fields +============= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: synchronous, asynchronous + +Overview +-------- + +In this guide, you can learn how to use the {+driver-long+} to update the +values of fields in MongoDB documents. + +The {+driver-short+} provides the following methods to update fields: + +- ``UpdateOne()`` or ``UpdateOneAsync()`` + +.. tip:: Interactive Lab + + This page includes a short interactive lab that demonstrates how to + modify data by using the ``UpdateManyAsync()`` method. You can complete this + lab directly in your browser window without installing MongoDB or a code editor. + + To start the lab, click the :guilabel:`Open Interactive Tutorial` button at the + top of the page. To expand the lab to a full-screen format, click the + full-screen button (:guilabel:`â›¶`) in the top-right corner of the lab pane. + +.. note:: Method Overloads + + Many of the methods in this guide have multiple overloads. The examples + in this guide use the simplest overload for demonstration purposes. For + more information about the available overloads, see the + :manual:`{+new-api-root+} API documentation `. + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``restaurants`` collection +from the ``sample_restaurants`` database. The documents in this +collection use the following ``Restaurant``, ``Address``, and ``GradeEntry`` +classes as models: + +.. literalinclude:: /includes/code-examples/Restaurant.cs + :language: csharp + :copyable: + :dedent: + +.. literalinclude:: /includes/code-examples/Address.cs + :language: csharp + :copyable: + :dedent: + +.. literalinclude:: /includes/code-examples/GradeEntry.cs + :language: csharp + :copyable: + :dedent: + +.. include:: /includes/convention-pack-note.rst + +This collection is from the :atlas:`sample datasets ` provided +by Atlas. See the :ref:`` to learn how to create a free MongoDB cluster +and load this sample data. + +.. _csharp-update-operation: + +Single Values +------------- + +The {+driver-short+} supports the field update operators described in the +:manual:`{+mdb-server+} manual `. To specify an +update operation, call the corresponding method from the ``Builders.Update`` property. +The following sections describe these methods in more detail. + +Increment a Value +~~~~~~~~~~~~~~~~~ + +To increment the value of a field by a specific amount, call the ``Builders.Update.Inc()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to increment. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The amount to increment the field by. + + **Data Type:** ``TField`` + +Set If Lower or Greater +~~~~~~~~~~~~~~~~~~~~~~~ + +To update the value of the field to a specified value, *but only if the specified value +is greater than the current value of the field,* call the ``Builders.Update.Max()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The value to set the field to. + + **Data Type:** ``TField`` + +To update the value of the field to a specified value, *but only if the specified value +is lesser than the current value of the field,* call the ``Builders.Update.Min()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The value to set the field to. + + **Data Type:** ``TField`` + +Multiply a Value +~~~~~~~~~~~~~~~~ + +To multiply the value of a field by a specific amount, call the ``Builders.Update.Mul()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The amount to multiply the field by. + + **Data Type:** ``TField`` + +Rename a Field +~~~~~~~~~~~~~~ + +To rename a field, call the ``Builders.Update.Rename()`` method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to rename. + + **Data Type:** ``Expression>`` + + * - ``newName`` + - The new name for the field. + + **Data Type:** ``string`` + +Set a Value +~~~~~~~~~~~ + +To set the value of a field to a specific value, call the ``Builders.Update.Set()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The value to set the field to. + + **Data Type:** ``TField`` + +Unset a Field +~~~~~~~~~~~~~ + +To remove a field from a document, call the ``Builders.Update.Unset()`` method. This method accepts the following parameter: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to remove. + + **Data Type:** ``Expression>`` + +Set on Insert +~~~~~~~~~~~~~ + +To set the value of a field only if the document is an upsert, call the ``Builders.Update.SetOnInsert()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The value to set the field to. + + **Data Type:** ``TField`` + +Set the Current Date +~~~~~~~~~~~~~~~~~~~~ + +To set the value of a field to the current date and time, call the ``Builders.Update.CurrentDate()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``type`` + - The format of the date and time, defined in the ``UpdateDefinitionCurrentDateType`` + enum. The default value is ``null``. + + **Data Type:** `UpdateDefinitionCurrentDateType? <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionCurrentDateType.html>`__ + +The following code example performs these steps: + +1. Creates a query filter that matches documents where the value of the ``name`` field + is "Bagels N Buns". +#. Creates an update definition that sets the value of the ``name`` field to "2 Bagels 2 Buns". +#. Calls the ``UpdateOne()`` method to update the document. + +Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding +code. + +.. tabs:: + + .. tab:: Synchronous + :tabid: update-one-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one + :end-before: // end-update-one + + .. tab:: Asynchronous + :tabid: update-one-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneAsync.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-async + :end-before: // end-update-one-async + diff --git a/source/fundamentals/crud/write-operations/update/update-one.txt b/source/fundamentals/crud/write-operations/update/update-one.txt deleted file mode 100644 index 4943e724..00000000 --- a/source/fundamentals/crud/write-operations/update/update-one.txt +++ /dev/null @@ -1,841 +0,0 @@ -.. _csharp-update-one: - -================ -Update Documents -================ - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: synchronous, asynchronous - -Overview --------- - -In this guide, you can learn how to use the {+driver-long+} to update the -values of fields in MongoDB documents. - -The {+driver-short+} provides the following methods to update fields: - -- ``UpdateOne()`` or ``UpdateOneAsync()`` - -.. tip:: Interactive Lab - - This page includes a short interactive lab that demonstrates how to - modify data by using the ``UpdateManyAsync()`` method. You can complete this - lab directly in your browser window without installing MongoDB or a code editor. - - To start the lab, click the :guilabel:`Open Interactive Tutorial` button at the - top of the page. To expand the lab to a full-screen format, click the - full-screen button (:guilabel:`â›¶`) in the top-right corner of the lab pane. - -.. note:: Method Overloads - - Many of the methods in this guide have multiple overloads. The examples - in this guide use the simplest overload for demonstration purposes. For - more information about the available overloads, see the - :manual:`{+new-api-root+} API documentation `. - -Sample Data -~~~~~~~~~~~ - -The examples in this guide use the ``restaurants`` collection -from the ``sample_restaurants`` database. The documents in this -collection use the following ``Restaurant``, ``Address``, and ``GradeEntry`` -classes as models: - -.. literalinclude:: /includes/code-examples/Restaurant.cs - :language: csharp - :copyable: - :dedent: - -.. literalinclude:: /includes/code-examples/Address.cs - :language: csharp - :copyable: - :dedent: - -.. literalinclude:: /includes/code-examples/GradeEntry.cs - :language: csharp - :copyable: - :dedent: - -.. include:: /includes/convention-pack-note.rst - -This collection is from the :atlas:`sample datasets ` provided -by Atlas. See the :ref:`` to learn how to create a free MongoDB cluster -and load this sample data. - -.. _csharp-update-operation: - -Update Methods and Parameters ------------------------------- - -To update one or more fields in a MongoDB document, call the ``UpdateOne()`` or -``UpdateOneAsync()`` method. These methods accept the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``filter`` - - A *query filter* that specifies the document to update. You can use the - ``Builders`` class to create a query filter. For more information about - query filters, see the - :manual:`{+mdb-server+} manual `. - - **Data Type:** `FilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ - - * - ``update`` - - An instance of the ``UpdateDefinition`` class. This object specifies the kind of update - operation, the fields to update, and the new value for each field. You can use the - ``Builders`` class to create an ``UpdateDefinition`` object. - - **Data Type:** `UpdateDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinition-1.html>`__ - - * - ``options`` - - *Optional.* An instance of the ``UpdateOptions`` class that specifies the - configuration for the update operation. The default value is ``null``. - - **Data Type:** `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ - - * - ``cancellationToken`` - - *Optional.* A token that you can use to cancel the operation. - - **Data type**: `CancellationToken `__ - -.. To update one or more documents in a MongoDB collection, perform the following steps: - -.. 1. Create a query filter that specifies the documents to update. Link out to the query filter page. -.. #. Create an update definition that specifies the fields to update and the new values. Covered later. -.. #. Call the ``UpdateOne()`` or ``UpdateOneAsync()`` method to update the document. - -The following sections describe how to create update definitions for different operations. - -Single Values -------------- - -The {+driver-short+} supports the field update operators described in the -:manual:`{+mdb-server+} manual `. To specify an -update operation, call the corresponding method from the ``Builders.Update`` property. -The following sections describe these methods in more detail. - -Increment a Value -~~~~~~~~~~~~~~~~~ - -To increment the value of a field by a specific amount, call the ``Builders.Update.Inc()`` -method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to increment. - - **Data Type:** ``Expression>`` - - * - ``value`` - - The amount to increment the field by. - - **Data Type:** ``TField`` - -Set If Lower or Greater -~~~~~~~~~~~~~~~~~~~~~~~ - -To update the value of the field to a specified value, *but only if the specified value -is greater than the current value of the field,* call the ``Builders.Update.Max()`` -method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to update. - - **Data Type:** ``Expression>`` - - * - ``value`` - - The value to set the field to. - - **Data Type:** ``TField`` - -To update the value of the field to a specified value, *but only if the specified value -is lesser than the current value of the field,* call the ``Builders.Update.Min()`` -method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to update. - - **Data Type:** ``Expression>`` - - * - ``value`` - - The value to set the field to. - - **Data Type:** ``TField`` - -Multiply a Value -~~~~~~~~~~~~~~~~ - -To multiply the value of a field by a specific amount, call the ``Builders.Update.Mul()`` -method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to update. - - **Data Type:** ``Expression>`` - - * - ``value`` - - The amount to multiply the field by. - - **Data Type:** ``TField`` - -Rename a Field -~~~~~~~~~~~~~~ - -To rename a field, call the ``Builders.Update.Rename()`` method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to rename. - - **Data Type:** ``Expression>`` - - * - ``newName`` - - The new name for the field. - - **Data Type:** ``string`` - -Set a Value -~~~~~~~~~~~ - -To set the value of a field to a specific value, call the ``Builders.Update.Set()`` -method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to update. - - **Data Type:** ``Expression>`` - - * - ``value`` - - The value to set the field to. - - **Data Type:** ``TField`` - -Unset a Field -~~~~~~~~~~~~~ - -To remove a field from a document, call the ``Builders.Update.Unset()`` method. This method accepts the following parameter: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to remove. - - **Data Type:** ``Expression>`` - -Set on Insert -~~~~~~~~~~~~~ - -To set the value of a field only if the document is an upsert, call the ``Builders.Update.SetOnInsert()`` -method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to update. - - **Data Type:** ``Expression>`` - - * - ``value`` - - The value to set the field to. - - **Data Type:** ``TField`` - -Set the Current Date -~~~~~~~~~~~~~~~~~~~~ - -To set the value of a field to the current date and time, call the ``Builders.Update.CurrentDate()`` -method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to update. - - **Data Type:** ``Expression>`` - - * - ``type`` - - The format of the date and time, defined in the ``UpdateDefinitionCurrentDateType`` - enum. The default value is ``null``. - - **Data Type:** `UpdateDefinitionCurrentDateType? <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionCurrentDateType.html>`__ - -The following code example performs these steps: - -1. Creates a query filter that matches documents where the value of the ``name`` field - is "Bagels N Buns". -#. Creates an update definition that sets the value of the ``name`` field to "2 Bagels 2 Buns". -#. Calls the ``UpdateOne()`` method to update the document. - -Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding -code. - -.. tabs:: - - .. tab:: Synchronous - :tabid: update-one-sync - - .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one - :end-before: // end-update-one - - .. tab:: Asynchronous - :tabid: update-one-async - - .. literalinclude:: /includes/code-examples/update-one/UpdateOneAsync.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-async - :end-before: // end-update-one-async - -.. tip:: Aggregation Pipelines in Update Operations - - If you are using MongoDB Version 4.2 or later, you can use aggregation - pipelines made up of a subset of aggregation stages in update operations. For - more information on the aggregation stages MongoDB supports in - aggregation pipelines used in update operations, see the tutorial about building - :manual:`updates with aggregation pipelines `. - -Arrays ------- - -The {+driver-short+} supports the array update operators and modifiers described in the -:manual:`{+mdb-server+} manual `. -To specify an update operation, call the corresponding method from the ``Builders.Update`` -property. The following sections describe these methods in more detail. - -Add One Value -~~~~~~~~~~~~~ - -To add one value to the end of an array, call the ``Builders.Update.Push()`` method. -This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to add to. - - **Data Type:** ``Expression>>`` - - * - ``value`` - - The value to add to the end of the array field. - - **Data Type:** ``TItem`` - -The following code example pushes a new ``GradeEntry`` object into the ``Grades`` -array in the matching document. Select the :guilabel:`Synchronous` or -:guilabel:`Asynchronous` tab to see the corresponding code. - -.. tabs:: - - .. tab:: Synchronous - :tabid: update-one-array-sync - - .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-array - :end-before: // end-update-one-array - - .. tab:: Asynchronous - :tabid: update-one-array-async - - .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-array-async - :end-before: // end-update-one-array-async - -To add one value to the end of an array, *but only if it doesn't already exist in the array*, -call the ``Builders.Update.AddToSet()`` method. -This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to add to. - - **Data Type:** ``Expression>>`` - - * - ``value`` - - The value to add to the end of the array field. - - **Data Type:** ``TItem`` - -The following code example pushes a new ``GradeEntry`` object into the ``Grades`` -array in the matching document. Select the :guilabel:`Synchronous` or -:guilabel:`Asynchronous` tab to see the corresponding code. - -.. tip:: Specify a Position - - To add a value at a specific position in an array, call the ``PushEach()`` method. - -Add Multiple Values -~~~~~~~~~~~~~~~~~~~ - -To add multiple values to an array, call the ``Builders.Update.PushEach()`` method. -This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to add to. - - **Data Type:** ``Expression>>`` - - * - ``values`` - - The values to add to the array field. - - **Data Type:** ``IEnumerable`` - - * - ``slice`` - - The number of elements to keep in the array. If the value is negative, the - method keeps the specified number of elements from the end of the array. - - **Data Type:** ``int?`` - - * - ``position`` - - The position in the array at which to add the values. - - **Data Type:** ``int?`` - - * - ``sort`` - - The values to add to the array field. - - **Data Type:** `SortDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.SortDefinition-1.html>`__ - -To add multiple values to an array only if they aren't there, call the -``Builders.Update.AddToSetEach()`` method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to add to. - - **Data Type:** ``Expression>>`` - - * - ``values`` - - The values to add to the array field. - - **Data Type:** ``IEnumerable`` - -Remove Values -~~~~~~~~~~~~~ - -To remove the first value from an array, call the ``Builders.Update.PopFirst()`` method. -This method accepts the following parameter: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to remove the first value from. - - **Data Type:** ``Expression>>`` - -To remove the last value from an array, call the ``Builders.Update.PopLast()`` method: -This method accepts the following parameter: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to remove the last value from. - - **Data Type:** ``Expression>>`` - -To remove all instances of a specific value from an array, call the ``Builders.Update.Pull()`` method: -This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to add to. - - **Data Type:** ``Expression>>`` - - * - ``value`` - - The value to remove from the array field. - - **Data Type:** ``IEnumerable`` - -To remove all instances of more than one specific value from an array, call the ``Builders.Update.PullAll()`` method: -This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to add to. - - **Data Type:** ``Expression>>`` - - * - ``values`` - - The values to remove from the array field. - - **Data Type:** ``IEnumerable`` - -To remove all values that match a specific condition from an array, call the ``Builders.Update.PullFilter()`` method: -This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to add to. - - **Data Type:** ``Expression>>`` - - * - ``filter`` - - A query filter that specifies the condition for values to remove. - - **Data Type:** `FilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ - -Update Matching Elements -~~~~~~~~~~~~~~~~~~~~~~~~ - -To query and update specific elements in an array field, use -the :manual:`positional operator ` (``$``) -when you specify the field to update. -Combined with the ``Builders.Update.Set()`` method, you can use this operator to query -and update specific elements in an array field. - -To update the first array element that matches your query filter, use the -positional ``$`` operator. The array value must appear be part of the query filter. - -The following code example queries the ``restaurants`` collection for a document -that contains a grade of 2. It then updates that grade to 22 in the matching documents. -Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding code. - -To update all array elements in the matching documents, use the all positional operator -(``$[]``). - -The following code example queries the ``restaurants`` collection for a document -where the ``name`` is ``"Downtown Deli"``. It then updates all that grade to 22 in the matching documents. -Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding code. - -To update all array elements that match your query filter, use the all positional operator -(``$[]``). The array value must appear be part of the query filter. - -The following code example queries the ``restaurants`` collection for a document -that contains a grade of 2. It then updates that grade to 22 in the matching documents. - -Customize the Update Operation ------------------------------- - -The preceding update methods optionally accept an ``UpdateOptions`` object as an additional -parameter. You can use this argument to configure the update operation. - -The ``UpdateOptions`` class contains the following properties: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Property - - Description - - * - ``ArrayFilters`` - - Specifies which array elements to modify for an update operation on an array field. - See :manual:`the MongoDB server manual` - for more information. - - **Data Type:** IEnumerable<`ArrayFilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.ArrayFilterDefinition.html>`__> - - * - ``BypassDocumentValidation`` - - Specifies whether the update operation bypasses document validation. This lets you - update documents that don't meet the schema validation requirements, if any - exist. See :manual:`the MongoDB server manual` - for more information on schema validation. - - **Data Type:** ``bool?`` - - * - ``Collation`` - - Specifies the kind of language collation to use when sorting - results. See :manual:`the MongoDB server manual` - for more information on collation. - - **Data Type:** `Collation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Collation.html>`__ - - * - ``Comment`` - - Gets or sets the user-provided comment for the operation. - See :manual:`the MongoDB server manual` - for more information. - - **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ - - * - ``Hint`` - - Gets or sets the index to use to scan for documents. - See :manual:`the MongoDB server manual` - for more information. - - **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ - - * - ``IsUpsert`` - - Specifies whether the update operation performs an upsert operation if no - documents match the query filter. - See :manual:`the MongoDB server manual ` - for more information. - - **Data Type:** ``bool`` - - * - ``Let`` - - Gets or sets the let document. - See :manual:`the MongoDB server manual ` - for more information. - - **Data Type:** `BsonDocument <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonDocument.html>`__ - -Return Value ------------- - -The ``UpdateOne()`` and ``UpdateMany()`` methods return an ``UpdateResult`` -object. The ``UpdateOneAsync()`` and ``UpdateManyAsync()`` methods return an asynchronous -version of this type, a ``Task`` object. -The ``UpdateResult`` class contains the following properties: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Property - - Description - - * - ``IsAcknowledged`` - - Indicates whether the replace operation was acknowledged by MongoDB. - - **Data Type:** ``bool`` - - * - ``IsModifiedCountAvailable`` - - Indicates whether you can read the count of replaced records on the - ``ReplaceOneResult``. - - **Data Type:** ``bool`` - - * - ``MatchedCount`` - - The number of documents that matched the query filter, regardless of - whether one was replaced. - - **Data Type:** ``long`` - - * - ``ModifiedCount`` - - The number of documents replaced by the replace operation. - - **Data Type:** ``long`` - - * - ``UpsertedId`` - - The ID of the document that was upserted in the database, if the driver - performed an upsert. - - **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ - -Example -------- - -The following code uses the ``UpdateMany()`` method to find all documents where the -``borough`` field has the value "Manhattan", then updates the ``borough`` -value in these documents to "Manhattan (north)". Because the ``IsUpsert`` option is -set to ``true``, the driver inserts a new document if the query filter doesn't -match any existing documents. - -.. io-code-block:: - :copyable: true - - .. input:: - :language: csharp - - var filter = Builders.Filter - .Eq(restaurant => restaurant.Borough, "Manhattan"); - - var update = Builders.Update - .Set(restaurant => restaurant.Borough, "Manhattan (north)"); - - UpdateOptions opts = new UpdateOptions() - { - Comment = new BsonString("Borough updated for C# Driver Fundamentals"), - IsUpsert = true - }; - - Console.WriteLine("Updating documents..."); - var result = _restaurantsCollection.UpdateMany(filter, update, opts); - - Console.WriteLine($"Updated documents: {result.ModifiedCount}"); - Console.WriteLine($"Result acknowledged? {result.IsAcknowledged}"); - - .. output:: - :language: none - :visible: false - - Updating documents... - Updated documents: 10259 - Result acknowledged? True - -Multiple Updates ----------------- - -To combine multiple update definitions into one, call the ``Builders.Update.Combine()`` method. -This method accepts the following parameter: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``updates`` - - An array of update definitions to combine. - - **Data Type:** ``UpdateDefinition[]`` - -This method returns a single ``UpdateDefinition`` object, which you can then pass to the -``UpdateOne()`` or ``UpdateMany()`` method. - -.. _csharp-change-info: - -Additional Information ----------------------- - -For runnable examples of the update operations, see the following usage -examples: - -- :ref:`csharp-update-one` -- :ref:`csharp-update-many` - -To learn more about creating query filters, see the :ref:`csharp-specify-query` guide. - -API Documentation -~~~~~~~~~~~~~~~~~ - -To learn more about any of the methods or types discussed in this -guide, see the following API documentation: - -* `UpdateOne() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateOne.html>`__ -* `UpdateOneAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateOneAsync.html>`__ -* `UpdateMany() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateMany.html>`__ -* `UpdateManyAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateManyAsync.html>`__ -* `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ -* `UpdateResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateResult.html>`__ - -.. _csharp-update-instruqt-lab: - -.. instruqt:: /mongodb-docs/tracks/update-a-document---c-net-driver?token=em_69t_l-j0BC_en7Uy - :title: UpdateManyAsync() Lesson - :drawer: \ No newline at end of file diff --git a/source/includes/code-examples/update-many/UpdateMany.cs b/source/includes/code-examples/update-many/UpdateMany.cs index b8eb7317..ac807edb 100644 --- a/source/includes/code-examples/update-many/UpdateMany.cs +++ b/source/includes/code-examples/update-many/UpdateMany.cs @@ -18,7 +18,8 @@ public class UpdateMany public static void Main(string[] args) { - try { + try + { Setup(); // Prints extra space for console readability @@ -39,10 +40,12 @@ public static void Main(string[] args) ResetSampleData(); Console.WriteLine("done."); - // Prints a message if any exceptions occur during the operation - } catch (MongoException me) { + // Prints a message if any exceptions occur during the operation + } + catch (MongoException me) + { Console.WriteLine("Unable to update due to an error: " + me); - } + } } private static UpdateResult UpdateManyRestaurants() @@ -95,6 +98,35 @@ private static void ResetSampleData() _restaurantsCollection.UpdateMany(filter, update); } + public static void CombineUpdates() + { + // start-combine-sync + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var combinedUpdate = Builders.Update.Combine( + Builders.Update.Set("cuisine", "French"), + Builders.Update.PopLast("grades") + ); + + _restaurantsCollection.UpdateMany(filter, combinedUpdate); + // end-combine-sync + } + + public static async Task CombineUpdatesAsync() + { + // start-combine-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var combinedUpdate = Builders.Update.Combine( + Builders.Update.Set("cuisine", "French"), + Builders.Update.PopLast("grades") + ); + + await _restaurantsCollection.UpdateManyAsync(filter, combinedUpdate); + // end-combine-async + } } public class Restaurant diff --git a/source/includes/code-examples/update-one/UpdateOne.cs b/source/includes/code-examples/update-one/UpdateOne.cs index 30dacbd3..c9434afb 100644 --- a/source/includes/code-examples/update-one/UpdateOne.cs +++ b/source/includes/code-examples/update-one/UpdateOne.cs @@ -91,6 +91,36 @@ public static async Task UpdateOneRestaurantArrayAsync() // end-update-one-array-async } + public static void CombineUpdates() + { + // start-combine-sync + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var combinedUpdate = Builders.Update.Combine( + Builders.Update.Set("cuisine", "French"), + Builders.Update.PopLast("grades") + ); + + _restaurantsCollection.UpdateOne(filter, combinedUpdate); + // end-combine-sync + } + + public static async Task CombineUpdatesAsync() + { + // start-combine-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var combinedUpdate = Builders.Update.Combine( + Builders.Update.Set("cuisine", "French"), + Builders.Update.PopLast("grades") + ); + + await _restaurantsCollection.UpdateOneAsync(filter, combinedUpdate); + // end-combine-async + } + private static void Setup() { // Allows automapping of the camelCase database fields to models From 9ebc29884ad95ccb5b02a75b84292e23aa781327 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Wed, 20 Nov 2024 16:24:27 -0600 Subject: [PATCH 06/39] wip --- .../crud/write-operations/update.txt | 94 +++++++++++++++---- .../code-examples/update-many/UpdateMany.cs | 34 +++++++ .../code-examples/update-one/UpdateOne.cs | 34 +++++++ 3 files changed, 143 insertions(+), 19 deletions(-) diff --git a/source/fundamentals/crud/write-operations/update.txt b/source/fundamentals/crud/write-operations/update.txt index b0acbb49..a46b6af3 100644 --- a/source/fundamentals/crud/write-operations/update.txt +++ b/source/fundamentals/crud/write-operations/update.txt @@ -44,7 +44,7 @@ The following sections describe these methods in more detail. Many of the methods in this guide have multiple overloads. The examples in this guide use the simplest overload for demonstration purposes. For more information about the available overloads, see the - :manual:`{+new-api-root+} API documentation `. + `API documentation. {+new-api-root+}/index.html>`__ .. tip:: Interactive Lab @@ -73,7 +73,7 @@ methods all accept the following parameters: - An instance of the ``FilterDefinition`` class that specifies the documents to update. To learn how to create a query filter, see :ref:`csharp-specify-query`. - **Data Type:** `FilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ + **Data Type:** `FilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ * - ``update`` - An instance of the ``UpdateDefinition`` class. This object specifies the kind of update @@ -99,8 +99,8 @@ Update Multiple Values ---------------------- The ``UpdateOne()``, ``UpdateOneAsync()``, ``UpdateMany()``, and ``UpdateManyAsync()`` -methods each accept one ``UpdateDefinition`` object. The following sections describe how -to multiple values in a single method call. +methods each accept only one ``UpdateDefinition`` object. The following sections describe how +to update multiple values in a single method call. Combine Update Definitions ~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -124,13 +124,13 @@ The ``Combine()`` method returns a single ``UpdateDefinition`` object that defin multiple update operations. The following code example uses the ``Combine()`` method to combine a -:manual:`$set ` operation and a -:manual:`$pop ` +:manual:`$set ` operation and an +:manual:`$unset ` operation: .. tabs:: - .. tab:: UpdateOne (Synchronous) + .. tab:: UpdateOne (Sync) :tabid: update-one-sync .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs @@ -140,7 +140,7 @@ operation: :start-after: // start-combine-sync :end-before: // end-combine-sync - .. tab:: UpdateOne (Asynchronous) + .. tab:: UpdateOne (Async) :tabid: update-one-async .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs @@ -150,7 +150,7 @@ operation: :start-after: // start-combine-async :end-before: // end-combine-async - .. tab:: UpdateMany (Synchronous) + .. tab:: UpdateMany (Sync) :tabid: update-many-sync .. literalinclude:: /includes/code-examples/update-many/UpdateMany.cs @@ -160,7 +160,7 @@ operation: :start-after: // start-combine-sync :end-before: // end-combine-sync - .. tab:: UpdateMany (Asynchronous) + .. tab:: UpdateMany (Async) :tabid: update-many-async .. literalinclude:: /includes/code-examples/update-many/UpdateMany.cs @@ -173,8 +173,12 @@ operation: Update Pipelines ~~~~~~~~~~~~~~~~ -Builders.Update.Pipeline is used to create an update pipeline for MongoDB update operations. An update pipeline allows you to specify a sequence of update stages that modify the documents in a collection. Each stage in the pipeline is an update operation that transforms the document in some way. This is similar to the aggregation pipeline but is used specifically for updates. -This method accepts the following parameter: +If your application connects to {+mdb-server+} 4.2 or later, you can join +a sequence of update operations into a single +:manual:`aggregation pipeline. ` + +To create an update pipeline, call the ``Builders.Update.Pipeline()`` method. This method +accepts the following parameter: .. list-table:: :widths: 30 70 @@ -184,17 +188,69 @@ This method accepts the following parameter: - Description * - ``pipeline`` - - A ``PipelineDefinition`` instance that specifies the update pipeline. + - A ``PipelineDefinition`` instance that represents the update pipeline. To create + a ``PipelineDefinition`` object, create a BSON object for each update operation you + want to perform, then pass these objects to the ``Pipeline.Create()`` method. **Data Type:** ``PipelineDefinition`` -.. tip:: Aggregation Pipelines in Update Operations +The ``Pipeline()`` method returns a single ``UpdateDefinition`` object that defines +multiple aggregation stages. + +The following code example uses the ``Pipeline()`` method to combine a +:manual:`$set ` operation and an +:manual:`$unset ` +operation: + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-pipeline-sync + :end-before: // end-pipeline-sync + + .. tab:: UpdateOne (Async) + :tabid: update-one-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-pipeline-async + :end-before: // end-pipeline-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-sync + + .. literalinclude:: /includes/code-examples/update-many/UpdateMany.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-pipeline-sync + :end-before: // end-pipeline-sync + + .. tab:: UpdateMany (Async) + :tabid: update-many-async + + .. literalinclude:: /includes/code-examples/update-many/UpdateMany.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-pipeline-async + :end-before: // end-pipeline-async + +.. note:: Unsupported Operations - If you are using MongoDB Version 4.2 or later, you can use aggregation - pipelines made up of a subset of aggregation stages in update operations. For - more information on the aggregation stages MongoDB supports in - aggregation pipelines used in update operations, see the tutorial about building - :manual:`updates with aggregation pipelines `. + Update pipelines don't support all update operations, but they do support certain + aggregation stages not found in other update definitions. For a list of + update operations supported by pipelines, see + :manual:`Updates with Aggregation Pipeline ` + in the {+mdb-server+} manual. .. _csharp-update-options: diff --git a/source/includes/code-examples/update-many/UpdateMany.cs b/source/includes/code-examples/update-many/UpdateMany.cs index ac807edb..d4e0d288 100644 --- a/source/includes/code-examples/update-many/UpdateMany.cs +++ b/source/includes/code-examples/update-many/UpdateMany.cs @@ -127,6 +127,40 @@ public static async Task CombineUpdatesAsync() await _restaurantsCollection.UpdateManyAsync(filter, combinedUpdate); // end-combine-async } + public static void PipelineUpdate() + { + // start-pipeline-sync + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var updatePipeline = Builders.Update.Pipeline( + PipelineDefinition.Create( + new BsonDocument("$set", new BsonDocument("cuisine", "French")), + new BsonDocument("$unset", "borough") + ) + ); + + _restaurantsCollection.UpdateMany(filter, updatePipeline); + // end-pipeline-sync + } + + public static async Task PipelineUpdateAsync() + { + // start-pipeline-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var updatePipeline = Builders.Update.Pipeline( + PipelineDefinition.Create( + new BsonDocument("$set", new BsonDocument("cuisine", "French")), + new BsonDocument("$unset", "borough") + ) + ); + + await _restaurantsCollection.UpdateManyAsync(filter, updatePipeline); + // end-pipeline-async + } + } public class Restaurant diff --git a/source/includes/code-examples/update-one/UpdateOne.cs b/source/includes/code-examples/update-one/UpdateOne.cs index c9434afb..a5c1a022 100644 --- a/source/includes/code-examples/update-one/UpdateOne.cs +++ b/source/includes/code-examples/update-one/UpdateOne.cs @@ -121,6 +121,40 @@ public static async Task CombineUpdatesAsync() // end-combine-async } + public static void PipelineUpdate() + { + // start-pipeline-sync + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var updatePipeline = Builders.Update.Pipeline( + PipelineDefinition.Create( + new BsonDocument("$set", new BsonDocument("cuisine", "French")), + new BsonDocument("$unset", "borough") + ) + ); + + _restaurantsCollection.UpdateOne(filter, updatePipeline); + // end-pipeline-sync + } + + public static async Task PipelineUpdateAsync() + { + // start-pipeline-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var updatePipeline = Builders.Update.Pipeline( + PipelineDefinition.Create( + new BsonDocument("$set", new BsonDocument("cuisine", "French")), + new BsonDocument("$unset", "borough") + ) + ); + + await _restaurantsCollection.UpdateOneAsync(filter, updatePipeline); + // end-pipeline-async + } + private static void Setup() { // Allows automapping of the camelCase database fields to models From a2498036a5db921d4e2f24b1a55f30ecb2c6f8cb Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Wed, 20 Nov 2024 16:33:32 -0600 Subject: [PATCH 07/39] wip --- .../crud/write-operations/update.txt | 10 ++--- .../crud/write-operations/update/fields.txt | 37 ++++++++----------- 2 files changed, 20 insertions(+), 27 deletions(-) diff --git a/source/fundamentals/crud/write-operations/update.txt b/source/fundamentals/crud/write-operations/update.txt index a46b6af3..e54baecc 100644 --- a/source/fundamentals/crud/write-operations/update.txt +++ b/source/fundamentals/crud/write-operations/update.txt @@ -125,7 +125,7 @@ multiple update operations. The following code example uses the ``Combine()`` method to combine a :manual:`$set ` operation and an -:manual:`$unset ` +:manual:`$unset ` operation: .. tabs:: @@ -257,11 +257,8 @@ operation: Customize the Update Operation ------------------------------ -To combine multiple update definitions into one, call the ``Builders.Update.Combine()`` method. -This method accepts the following parameter: - -The preceding update methods optionally accept an ``UpdateOptions`` object as an additional -parameter. You can use this argument to configure the update operation. +The update methods optionally accept an ``UpdateOptions`` object as a +parameter. You can use this argument to customize the update operation. The ``UpdateOptions`` class contains the following properties: @@ -278,6 +275,7 @@ The ``UpdateOptions`` class contains the following properties: for more information. **Data Type:** IEnumerable<`ArrayFilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.ArrayFilterDefinition.html>`__> + **Data Type**: Action<`ClusterBuilder <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Configuration.ClusterBuilder.html>`__> * - ``BypassDocumentValidation`` - Specifies whether the update operation bypasses document validation. This lets you diff --git a/source/fundamentals/crud/write-operations/update/fields.txt b/source/fundamentals/crud/write-operations/update/fields.txt index 8d29610c..ff4c2f67 100644 --- a/source/fundamentals/crud/write-operations/update/fields.txt +++ b/source/fundamentals/crud/write-operations/update/fields.txt @@ -20,12 +20,15 @@ Update Fields Overview -------- -In this guide, you can learn how to use the {+driver-long+} to update the -values of fields in MongoDB documents. +On this page, you can learn how to use the {+driver-long+} to update +fields in MongoDB documents. This page describes how to create ``UpdateDefinition`` +objects that specify the update operations you want to perform on fields. +You can pass these objects to the update methods described on *this page.* -The {+driver-short+} provides the following methods to update fields: - -- ``UpdateOne()`` or ``UpdateOneAsync()`` +The {+driver-short+} supports the field update operators described in the +:manual:`{+mdb-server+} manual `. To specify an +update operation, call the corresponding method from the ``Builders.Update`` property. +The following sections describe these methods in more detail. .. tip:: Interactive Lab @@ -75,16 +78,8 @@ and load this sample data. .. _csharp-update-operation: -Single Values -------------- - -The {+driver-short+} supports the field update operators described in the -:manual:`{+mdb-server+} manual `. To specify an -update operation, call the corresponding method from the ``Builders.Update`` property. -The following sections describe these methods in more detail. - Increment a Value -~~~~~~~~~~~~~~~~~ +----------------- To increment the value of a field by a specific amount, call the ``Builders.Update.Inc()`` method. This method accepts the following parameters: @@ -107,7 +102,7 @@ method. This method accepts the following parameters: **Data Type:** ``TField`` Set If Lower or Greater -~~~~~~~~~~~~~~~~~~~~~~~ +----------------------- To update the value of the field to a specified value, *but only if the specified value is greater than the current value of the field,* call the ``Builders.Update.Max()`` @@ -152,7 +147,7 @@ method. This method accepts the following parameters: **Data Type:** ``TField`` Multiply a Value -~~~~~~~~~~~~~~~~ +--------------- To multiply the value of a field by a specific amount, call the ``Builders.Update.Mul()`` method. This method accepts the following parameters: @@ -175,7 +170,7 @@ method. This method accepts the following parameters: **Data Type:** ``TField`` Rename a Field -~~~~~~~~~~~~~~ +-------------- To rename a field, call the ``Builders.Update.Rename()`` method. This method accepts the following parameters: @@ -197,7 +192,7 @@ To rename a field, call the ``Builders.Update.Rename()`` method. This method acc **Data Type:** ``string`` Set a Value -~~~~~~~~~~~ +----------- To set the value of a field to a specific value, call the ``Builders.Update.Set()`` method. This method accepts the following parameters: @@ -220,7 +215,7 @@ method. This method accepts the following parameters: **Data Type:** ``TField`` Unset a Field -~~~~~~~~~~~~~ +------------- To remove a field from a document, call the ``Builders.Update.Unset()`` method. This method accepts the following parameter: @@ -237,7 +232,7 @@ To remove a field from a document, call the ``Builders.Update.Unset()`` method. **Data Type:** ``Expression>`` Set on Insert -~~~~~~~~~~~~~ +------------- To set the value of a field only if the document is an upsert, call the ``Builders.Update.SetOnInsert()`` method. This method accepts the following parameters: @@ -260,7 +255,7 @@ method. This method accepts the following parameters: **Data Type:** ``TField`` Set the Current Date -~~~~~~~~~~~~~~~~~~~~ +-------------------- To set the value of a field to the current date and time, call the ``Builders.Update.CurrentDate()`` method. This method accepts the following parameters: From 3f5cec0271e4a666a5ab7bbe569c41676b91991f Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Wed, 20 Nov 2024 16:37:50 -0600 Subject: [PATCH 08/39] link fixes --- source/fundamentals/crud/write-operations/update.txt | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/source/fundamentals/crud/write-operations/update.txt b/source/fundamentals/crud/write-operations/update.txt index e54baecc..775e6839 100644 --- a/source/fundamentals/crud/write-operations/update.txt +++ b/source/fundamentals/crud/write-operations/update.txt @@ -44,7 +44,7 @@ The following sections describe these methods in more detail. Many of the methods in this guide have multiple overloads. The examples in this guide use the simplest overload for demonstration purposes. For more information about the available overloads, see the - `API documentation. {+new-api-root+}/index.html>`__ + `API documentation. <{+new-api-root+}/index.html>`__ .. tip:: Interactive Lab @@ -73,7 +73,7 @@ methods all accept the following parameters: - An instance of the ``FilterDefinition`` class that specifies the documents to update. To learn how to create a query filter, see :ref:`csharp-specify-query`. - **Data Type:** `FilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ + **Data Type:** `FilterDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>` * - ``update`` - An instance of the ``UpdateDefinition`` class. This object specifies the kind of update @@ -189,8 +189,8 @@ accepts the following parameter: * - ``pipeline`` - A ``PipelineDefinition`` instance that represents the update pipeline. To create - a ``PipelineDefinition`` object, create a BSON object for each update operation you - want to perform, then pass these objects to the ``Pipeline.Create()`` method. + a ``PipelineDefinition`` object, create a BSON document for each update operation you + want to perform, then pass these documents to the ``Pipeline.Create()`` method. **Data Type:** ``PipelineDefinition`` @@ -274,8 +274,7 @@ The ``UpdateOptions`` class contains the following properties: See :manual:`the MongoDB server manual` for more information. - **Data Type:** IEnumerable<`ArrayFilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.ArrayFilterDefinition.html>`__> - **Data Type**: Action<`ClusterBuilder <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Configuration.ClusterBuilder.html>`__> + **Data Type:** IEnumerable<`ArrayFilterDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ArrayFilterDefinition.html>`__> * - ``BypassDocumentValidation`` - Specifies whether the update operation bypasses document validation. This lets you From 440ea50ce3eefcca61880c313f53210aed11da15 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Wed, 20 Nov 2024 16:41:19 -0600 Subject: [PATCH 09/39] wip --- .../crud/write-operations/update.txt | 47 ++----------------- 1 file changed, 3 insertions(+), 44 deletions(-) diff --git a/source/fundamentals/crud/write-operations/update.txt b/source/fundamentals/crud/write-operations/update.txt index 775e6839..ea9a6837 100644 --- a/source/fundamentals/crud/write-operations/update.txt +++ b/source/fundamentals/crud/write-operations/update.txt @@ -85,8 +85,8 @@ methods all accept the following parameters: * - ``options`` - *Optional.* An instance of the ``UpdateOptions`` class that specifies the - configuration for the update operation. The default value is ``null``. To learn - about the available options, see :ref:`csharp-update-options`. + configuration for the update operation. The default value is ``null``. For a list + of available option, see :ref:`csharp-update-options`. **Data Type:** `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ @@ -320,47 +320,6 @@ The ``UpdateOptions`` class contains the following properties: **Data Type:** `BsonDocument <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonDocument.html>`__ -Example -~~~~~~~ - -The following code uses the ``UpdateMany()`` method to find all documents where the -``borough`` field has the value "Manhattan", then updates the ``borough`` -value in these documents to "Manhattan (north)". Because the ``IsUpsert`` option is -set to ``true``, the driver inserts a new document if the query filter doesn't -match any existing documents. - -.. io-code-block:: - :copyable: true - - .. input:: - :language: csharp - - var filter = Builders.Filter - .Eq(restaurant => restaurant.Borough, "Manhattan"); - - var update = Builders.Update - .Set(restaurant => restaurant.Borough, "Manhattan (north)"); - - UpdateOptions opts = new UpdateOptions() - { - Comment = new BsonString("Borough updated for C# Driver Fundamentals"), - IsUpsert = true - }; - - Console.WriteLine("Updating documents..."); - var result = _restaurantsCollection.UpdateMany(filter, update, opts); - - Console.WriteLine($"Updated documents: {result.ModifiedCount}"); - Console.WriteLine($"Result acknowledged? {result.IsAcknowledged}"); - - .. output:: - :language: none - :visible: false - - Updating documents... - Updated documents: 10259 - Result acknowledged? True - Return Value ------------ @@ -402,7 +361,7 @@ The ``UpdateResult`` class contains the following properties: - The ID of the document that was upserted in the database, if the driver performed an upsert. - **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ + **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ Additional Information ---------------------- From 2c0e416e4ee459689b17e5b48189f7a4ac870671 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Thu, 21 Nov 2024 08:46:57 -0600 Subject: [PATCH 10/39] wip --- .../crud/write-operations/update.txt | 16 ++++---- .../crud/write-operations/update/arrays.txt | 39 ++++--------------- .../crud/write-operations/update/fields.txt | 3 +- 3 files changed, 17 insertions(+), 41 deletions(-) diff --git a/source/fundamentals/crud/write-operations/update.txt b/source/fundamentals/crud/write-operations/update.txt index ea9a6837..ab3d3074 100644 --- a/source/fundamentals/crud/write-operations/update.txt +++ b/source/fundamentals/crud/write-operations/update.txt @@ -93,7 +93,7 @@ methods all accept the following parameters: * - ``cancellationToken`` - *Optional.* A token that you can use to cancel the operation. - **Data type**: `CancellationToken `__ + **Data type**: ``CancellationToken`` Update Multiple Values ---------------------- @@ -102,8 +102,8 @@ The ``UpdateOne()``, ``UpdateOneAsync()``, ``UpdateMany()``, and ``UpdateManyAsy methods each accept only one ``UpdateDefinition`` object. The following sections describe how to update multiple values in a single method call. -Combine Update Definitions -~~~~~~~~~~~~~~~~~~~~~~~~~~ +Combined Update Definitions +~~~~~~~~~~~~~~~~~~~~~~~~~~~ The ``Builders.Update.Combine()`` method lets you combine multiple ``UpdateDefinition`` objects. This method accepts the following parameter: @@ -190,7 +190,7 @@ accepts the following parameter: * - ``pipeline`` - A ``PipelineDefinition`` instance that represents the update pipeline. To create a ``PipelineDefinition`` object, create a BSON document for each update operation you - want to perform, then pass these documents to the ``Pipeline.Create()`` method. + want to perform, then pass these documents to the ``PipelineDefinition.Create()`` method. **Data Type:** ``PipelineDefinition`` @@ -199,7 +199,7 @@ multiple aggregation stages. The following code example uses the ``Pipeline()`` method to combine a :manual:`$set ` operation and an -:manual:`$unset ` +:manual:`$unset ` operation: .. tabs:: @@ -254,11 +254,11 @@ operation: .. _csharp-update-options: -Customize the Update Operation ------------------------------- +Configuration Options +--------------------- The update methods optionally accept an ``UpdateOptions`` object as a -parameter. You can use this argument to customize the update operation. +parameter. You can use this argument to configure the update operation. The ``UpdateOptions`` class contains the following properties: diff --git a/source/fundamentals/crud/write-operations/update/arrays.txt b/source/fundamentals/crud/write-operations/update/arrays.txt index bffb2f8e..28f26863 100644 --- a/source/fundamentals/crud/write-operations/update/arrays.txt +++ b/source/fundamentals/crud/write-operations/update/arrays.txt @@ -23,7 +23,8 @@ Overview On this page, you can learn how to use the {+driver-long+} to update array fields in MongoDB documents. This page describes how to create ``UpdateDefinition`` objects that specify the update operations you want to perform on array fields. -You can pass these objects to the update methods described on *this page.* +You can pass these objects to the update methods described on the +:ref:`` page. The {+driver-short+} supports the array update operators and modifiers described in the :manual:`{+mdb-server+} manual `. @@ -325,17 +326,17 @@ To update all array elements that match your query filter, use the all positiona The following code example queries the ``restaurants`` collection for a document that contains a grade of 2. It then updates that grade to 22 in the matching documents. - -Updating Documents with LINQ3 ------------------------------ +LINQ3 Provider +~~~~~~~~~~~~~~ LINQ syntax contains a positional operator (``$``) that you can use to update elements in an array field. Previous versions of the {+driver-short+} supported both the LINQ2 and LINQ3 providers. In LINQ2, you could use ``-1`` to indicate use of the positional operator. For example, the ``Restaurant`` class contains an array field named ``Grades`` that -contains multiple ``GradeEntry`` elements. The following code sample uses LINQ2 to update the -``Grade`` field of the first element in the ``Grades`` array: +contains multiple ``GradeEntry`` elements. If your application were using the LINQ2 +provider, you could use the following code sample to update the +``Grade`` field of the first element in this array: .. code-block:: csharp :linenos: @@ -372,29 +373,3 @@ contains multiple ``GradeEntry`` elements. The following code sample uses LINQ2 Builders.Update.Set(l => l.AnArrayMember.ElementAt(-1).Deleted, true)); This no longer works in LINQ3. Instead, you must use the following syntax: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Elements to Match - * - LINQ Syntax - - {+driver-short+} Syntax - - * - First matching element - * - ``array.$`` - - | Specifies the positional operator in LINQ3. - See :manual:`the MongoDB server manual` - for more information. - - * - All elements - * - ``array.$[]`` - - | Specifies the positional operator in LINQ3. - See :manual:`the MongoDB server manual` - for more information. - - * - All matching elements - * - ``array.$[]`` - - | Specifies the positional operator in LINQ3. - See :manual:`the MongoDB server manual` - for more information. \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations/update/fields.txt b/source/fundamentals/crud/write-operations/update/fields.txt index ff4c2f67..6f69d411 100644 --- a/source/fundamentals/crud/write-operations/update/fields.txt +++ b/source/fundamentals/crud/write-operations/update/fields.txt @@ -23,7 +23,8 @@ Overview On this page, you can learn how to use the {+driver-long+} to update fields in MongoDB documents. This page describes how to create ``UpdateDefinition`` objects that specify the update operations you want to perform on fields. -You can pass these objects to the update methods described on *this page.* +You can pass these objects to the update methods described on the +:ref:`` page. The {+driver-short+} supports the field update operators described in the :manual:`{+mdb-server+} manual `. To specify an From e9c1d3863ad7b571373406af694d280ce75ffb67 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Thu, 21 Nov 2024 12:02:35 -0600 Subject: [PATCH 11/39] wip --- .../crud/write-operations/update/arrays.txt | 223 ++++++++++++------ source/includes/atlas-sample-data.rst | 28 +++ source/includes/method-overloads.rst | 6 + 3 files changed, 191 insertions(+), 66 deletions(-) create mode 100644 source/includes/atlas-sample-data.rst create mode 100644 source/includes/method-overloads.rst diff --git a/source/fundamentals/crud/write-operations/update/arrays.txt b/source/fundamentals/crud/write-operations/update/arrays.txt index 28f26863..534ac61d 100644 --- a/source/fundamentals/crud/write-operations/update/arrays.txt +++ b/source/fundamentals/crud/write-operations/update/arrays.txt @@ -20,52 +20,22 @@ Update Arrays Overview -------- -On this page, you can learn how to use the {+driver-long+} to update array -fields in MongoDB documents. This page describes how to create ``UpdateDefinition`` -objects that specify the update operations you want to perform on array fields. -You can pass these objects to the update methods described on the -:ref:`` page. +On this page, you can learn how to create ``UpdateDefinition`` objects for array fields. +An ``UpdateDefinition`` object specifies the kind of update operation to perform, the +fields to update, and the new value for each field, if applicable. The {+driver-short+} supports the array update operators and modifiers described in the :manual:`{+mdb-server+} manual `. -To specify an update operation, call the corresponding method from the ``Builders.Update`` -property. The following sections describe these methods in more detail. +To create an ``UpdateDefinition`` object for one of these operators, call the corresponding +method from the ``Builders.Update`` property. +The following sections describe these methods in more detail. -.. note:: Method Overloads +After you create an ``UpdateDefinition``, pass it to one of the update methods +described on the :ref:`` page. - Many of the methods on this page have multiple overloads. The examples - in this guide show only one overload for each method. For - more information about the available overloads, see the - :manual:`{+new-api-root+} API documentation `. +.. include:: /includes/method-overloads.rst -Sample Data -~~~~~~~~~~~ - -The examples in this guide use the ``restaurants`` collection -from the ``sample_restaurants`` database. The documents in this -collection use the following ``Restaurant``, ``Address``, and ``GradeEntry`` -classes as models: - -.. literalinclude:: /includes/code-examples/Restaurant.cs - :language: csharp - :copyable: - :dedent: - -.. literalinclude:: /includes/code-examples/Address.cs - :language: csharp - :copyable: - :dedent: - -.. literalinclude:: /includes/code-examples/GradeEntry.cs - :language: csharp - :copyable: - :dedent: - -.. include:: /includes/convention-pack-note.rst - -This collection is from the :atlas:`sample datasets ` provided -by Atlas. See the :ref:`` to learn how to create a free MongoDB cluster -and load this sample data. +.. include:: /includes/atlas-sample-data.rst Add One Value ------------- @@ -90,35 +60,64 @@ This method accepts the following parameters: **Data Type:** ``TItem`` -The following code example pushes a new ``GradeEntry`` object into the ``Grades`` -array in the matching document. Select the :guilabel:`Synchronous` or -:guilabel:`Asynchronous` tab to see the corresponding code. +The following code example uses the ``Push()`` method to add a new ``GradeEntry`` object +to the ``Grades`` array in the matching documents: .. tabs:: - .. tab:: Synchronous - :tabid: update-one-array-sync + .. tab:: UpdateOne (Sync) + :tabid: update-one-push-sync - .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs + .. literalinclude:: /includes/code-examples/UpdateArrays.cs :language: csharp :copyable: true :dedent: - :start-after: // start-update-one-array - :end-before: // end-update-one-array + :start-after: // start-update-one-push + :end-before: // end-update-one-push - .. tab:: Asynchronous - :tabid: update-one-array-async + .. tab:: UpdateOne (Async) + :tabid: update-one-push-async - .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs + .. literalinclude:: /includes/code-examples/UpdateArrays.cs :language: csharp :copyable: true :dedent: - :start-after: // start-update-one-array-async - :end-before: // end-update-one-array-async + :start-after: // start-update-one-push-async + :end-before: // end-update-one-push-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-push-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-push + :end-before: // end-update-many-push + + .. tab:: UpdateMany (Async) + :tabid: update-many-push-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-push-async + :end-before: // end-update-many-push-async + +.. tip:: Configure the Push Operation + + To add a value at a specific position in an array, or to sort or slice the array after + updating it, call the ``PushEach()`` method instead. + TODO: link this To add one value to the end of an array, *but only if it doesn't already exist in the array*, -call the ``Builders.Update.AddToSet()`` method. -This method accepts the following parameters: +call the ``Builders.Update.AddToSet()`` method. +{+mdb-server+} determines whether the value already exists in the array by +comparing the value's BSON representation to the BSON representation of each +other element in the array. + +The ``AddToSet()`` method accepts the following parameters: .. list-table:: :widths: 30 70 @@ -137,13 +136,97 @@ This method accepts the following parameters: **Data Type:** ``TItem`` -The following code example pushes a new ``GradeEntry`` object into the ``Grades`` -array in the matching document. Select the :guilabel:`Synchronous` or -:guilabel:`Asynchronous` tab to see the corresponding code. +The following code example tries to use the ``AddToSet()`` method to re-add the first +``GradeEntry`` object to the ``Grades`` array in the matching documents. Because +the value already exists in the array, the update operation does nothing. -.. tip:: Specify a Position - - To add a value at a specific position in an array, call the ``PushEach()`` method. +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-addtoset-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-addtoset + :end-before: // end-update-one-addtoset + + .. tab:: UpdateOne (Async) + :tabid: update-one-addtoset-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-addtoset-async + :end-before: // end-update-one-addtoset-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-addtoset-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-addtoset + :end-before: // end-update-many-addtoset + + .. tab:: UpdateMany (Async) + :tabid: update-many-addtoset-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-addtoset-async + :end-before: // end-update-many-addtoset-async + +The following code example uses the ``PushEach()`` method to add two new ``GradeEntry`` +objects to the start of the ``Grades`` array. It then sorts the array elements in +descending order by the values of their ``Score`` fields. + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-pusheach-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pusheach + :end-before: // end-update-one-pusheach + + .. tab:: UpdateOne (Async) + :tabid: update-one-pusheach-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pusheach-async + :end-before: // end-update-one-pusheach-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-pusheach-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pusheach + :end-before: // end-update-many-pusheach + + .. tab:: UpdateMany (Async) + :tabid: update-many-pusheach-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pusheach-async + :end-before: // end-update-many-pusheach-async Add Multiple Values ------------------- @@ -169,20 +252,23 @@ This method accepts the following parameters: **Data Type:** ``IEnumerable`` * - ``slice`` - - The number of elements to keep in the array. If the value is negative, the - method keeps the specified number of elements from the end of the array. + - The number of elements to keep in the array, counted from the start of the array + after updates. If the value is negative, + the method keeps the specified number of elements from the end of the array. **Data Type:** ``int?`` * - ``position`` - - The position in the array at which to add the values. + - The position in the array at which to add the values. By default, the method + adds the values to the end of the array. **Data Type:** ``int?`` * - ``sort`` - - The values to add to the array field. + - A ``SortDefinition`` object that specifies how the driver sorts the array elements + after adding the new values. - **Data Type:** `SortDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.SortDefinition-1.html>`__ + **Data Type:** `SortDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.SortDefinition-1.html>`__ To add multiple values to an array only if they aren't there, call the ``Builders.Update.AddToSetEach()`` method. This method accepts the following parameters: @@ -204,6 +290,11 @@ To add multiple values to an array only if they aren't there, call the **Data Type:** ``IEnumerable`` +.. tip:: + + If you call the ``AddToSet()`` method with more than one value, the driver automatically + performs the operation as if you called the ``AddToSetEach()`` method. + Remove Values ------------- diff --git a/source/includes/atlas-sample-data.rst b/source/includes/atlas-sample-data.rst new file mode 100644 index 00000000..46d24320 --- /dev/null +++ b/source/includes/atlas-sample-data.rst @@ -0,0 +1,28 @@ +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``restaurants`` collection +from the ``sample_restaurants`` database. The documents in this +collection use the following ``Restaurant``, ``Address``, and ``GradeEntry`` +classes as models: + +.. literalinclude:: /includes/code-examples/Restaurant.cs + :language: csharp + :copyable: + :dedent: + +.. literalinclude:: /includes/code-examples/Address.cs + :language: csharp + :copyable: + :dedent: + +.. literalinclude:: /includes/code-examples/GradeEntry.cs + :language: csharp + :copyable: + :dedent: + +.. include:: /includes/convention-pack-note.rst + +This collection is from the :atlas:`sample datasets ` provided +by Atlas. See the :ref:`` to learn how to create a free MongoDB cluster +and load this sample data. \ No newline at end of file diff --git a/source/includes/method-overloads.rst b/source/includes/method-overloads.rst new file mode 100644 index 00000000..d70012f9 --- /dev/null +++ b/source/includes/method-overloads.rst @@ -0,0 +1,6 @@ +.. note:: Method Overloads + + Many of the methods on this page have multiple overloads. The examples + in this guide show only one overload for each method. For + more information about the available overloads, see the + :manual:`{+new-api-root+} API documentation `. \ No newline at end of file From c598b606fa927e419f902095d17b2c077457b980 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Thu, 21 Nov 2024 12:03:22 -0600 Subject: [PATCH 12/39] wip --- source/includes/code-examples/UpdateArrays.cs | 293 ++++++++++++++++++ 1 file changed, 293 insertions(+) create mode 100644 source/includes/code-examples/UpdateArrays.cs diff --git a/source/includes/code-examples/UpdateArrays.cs b/source/includes/code-examples/UpdateArrays.cs new file mode 100644 index 00000000..a7cc9bfd --- /dev/null +++ b/source/includes/code-examples/UpdateArrays.cs @@ -0,0 +1,293 @@ +using MongoDB.Bson; +using MongoDB.Bson.Serialization.Attributes; +using MongoDB.Bson.Serialization.Conventions; +using MongoDB.Driver; +using WriteData.Models; +using static System.Console; + +namespace CSharpExamples.WriteData; + +public static class UpdateArrays +{ + private static IMongoCollection _restaurantsCollection; + //private static string _mongoConnectionString = ""; + private static string _mongoConnectionString = + "mongodb+srv://mikewoofter:mikewoofter@cluster0.pw0q4.mongodb.net/?retryWrites=true&w=majority"; + + public static UpdateResult UpdateOneArrayPush() + { + // start-update-one-push + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var update = Builders.Update + .Push(restaurant => restaurant.Grades, new GradeEntry() + { + Date = DateTime.Now, + Grade = "A", + Score = 96 + }); + + var result = _restaurantsCollection.UpdateOne(filter, update); + + return result; + // end-update-one-push + } + + public static async Task UpdateOneArrayPushAsync() + { + // start-update-one-push-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var update = Builders.Update + .Push(restaurant => restaurant.Grades, new GradeEntry() + { + Date = DateTime.Now, + Grade = "A", + Score = 96 + }); + + var result = await _restaurantsCollection.UpdateOneAsync(filter, update); + + return result; + // end-update-one-push-async + } + + public static UpdateResult UpdateOneArrayAddToSet() + { + // start-update-one-addtoset + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var firstGradeEntry = _restaurantsCollection.Find(filter).FirstOrDefault().Grades[0]; + + var update = Builders.Update + .AddToSet(restaurant => restaurant.Grades, firstGradeEntry); + + var result = _restaurantsCollection.UpdateOne(filter, update); + + return result; + // end-update-one-addtoset + } + + public static async Task UpdateOneArrayAddToSetAsync() + { + // start-update-one-addtoset-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var firstGradeEntry = _restaurantsCollection.Find(filter).FirstOrDefault().Grades[0]; + + var update = Builders.Update + .AddToSet(restaurant => restaurant.Grades, firstGradeEntry); + + var result = await _restaurantsCollection.UpdateOneAsync(filter, update); + + return result; + // end-update-one-addtoset-async + } + + public static UpdateResult UpdateManyArrayAddToSet() + { + // start-update-many-addtoset + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var firstGradeEntry = _restaurantsCollection.Find(filter).FirstOrDefault().Grades[0]; + + var update = Builders.Update + .AddToSet(restaurant => restaurant.Grades, firstGradeEntry); + + var result = _restaurantsCollection.UpdateMany(filter, update); + + return result; + // end-update-many-addtoset + } + + public static async Task UpdateManyArrayAddToSetAsync() + { + // start-update-many-addtoset-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var firstGradeEntry = _restaurantsCollection.Find(filter).FirstOrDefault().Grades[0]; + + var update = Builders.Update + .AddToSet(restaurant => restaurant.Grades, firstGradeEntry); + + var result = await _restaurantsCollection.UpdateOneAsync(filter, update); + + return result; + // end-update-many-addtoset-async + } + + public static UpdateResult UpdateManyArrayPushEach() + { + // start-update-many-pusheach + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var newGrades = new List + { + new GradeEntry { Date = DateTime.Now, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89,} + }; + + var scoreSort = Builders.Sort.Descending(g => g.Score); + + var update = Builders.Update.PushEach( + "Grades", + newGrades, + position: 0, + sort: scoreSort); + + var result = _restaurantsCollection.UpdateMany(filter, update); + + return result; + // end-update-many-pusheach + } + + public static UpdateResult UpdateManyArrayPushEach() + { + // start-update-many-pusheach + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var newGrades = new List + { + new GradeEntry { Date = DateTime.Now, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89,} + }; + + var scoreSort = Builders.Sort.Descending(g => g.Score); + + var update = Builders.Update.PushEach( + "Grades", + newGrades, + position: 0, + sort: scoreSort); + + var result = _restaurantsCollection.UpdateMany(filter, update); + + return result; + // end-update-many-pusheach + } + + public static async Task UpdateManyArrayPushEachAsync() + { + // start-update-many-pusheach-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var firstGradeEntry = _restaurantsCollection.Find(filter).FirstOrDefault().Grades[0]; + + var update = Builders.Update + .AddToSet(restaurant => restaurant.Grades, firstGradeEntry); + + var result = await _restaurantsCollection.UpdateOneAsync(filter, update); + + return result; + // end-update-many-pusheach-async + } + + public static UpdateResult UpdateOneArrayPushEach() + { + // start-update-one-pusheach + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var newGrades = new List + { + new GradeEntry { Date = DateTime.Now, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89,} + }; + + var scoreSort = Builders.Sort.Descending(g => g.Score); + + var update = Builders.Update.PushEach( + "Grades", + newGrades, + position: 0, + sort: scoreSort); + + var result = _restaurantsCollection.UpdateOne(filter, update); + + return result; + // end-update-one-pusheach + } + public static async Task UpdateOneArrayPushEachAsync() + { + // start-update-one-pusheach-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var newGrades = new List + { + new GradeEntry { Date = DateTime.Now, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89,} + }; + + var scoreSort = Builders.Sort.Descending(g => g.Score); + + var update = Builders.Update.PushEach( + "Grades", + newGrades, + position: 0, + sort: scoreSort); + + var result = _restaurantsCollection.UpdateOneAsync(filter, update); + + return result; + // end-update-one-pusheach-async + } + + public static async Task UpdateOneArrayPushEachAsync() + { + // start-update-one-addtoset-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var firstGradeEntry = _restaurantsCollection.Find(filter).FirstOrDefault().Grades[0]; + + var update = Builders.Update + .AddToSet(restaurant => restaurant.Grades, firstGradeEntry); + + var result = await _restaurantsCollection.UpdateOneAsync(filter, update); + + return result; + // end-update-one-addtoset-async + } + + + // private static void LinqTest() + // { + // var x = _restaurantsCollection.UpdateOne(l => l.Id == another.Id && l.AnArrayMember.Any(l => l.Id == anArrayId), + // Builders.Update.Set(l => l.AnArrayMember.ElementAt(-1).Deleted, true)); + // + // Builders.Update. + // } + + public static void Setup() + { + // This allows automapping of the camelCase database fields to our models. + var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; + ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); + + // Establish the connection to MongoDB and get the restaurants database + var mongoClient = new MongoClient(_mongoConnectionString); + var restaurantsDatabase = mongoClient.GetDatabase("sample_restaurants"); + _restaurantsCollection = restaurantsDatabase.GetCollection("restaurants"); + } + + public static void ResetSampleData() + { + var filter = Builders.Filter + .Eq("name", "2 Bagels 2 Buns"); + + var update = Builders.Update + .Set(restaurant => restaurant.Name, "Bagels N Buns"); + + _restaurantsCollection.UpdateOne(filter, update); + } +} \ No newline at end of file From 3d9490b3acc7fbc70214d35f18225741c429477c Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Thu, 21 Nov 2024 12:17:48 -0600 Subject: [PATCH 13/39] fixes --- source/includes/code-examples/UpdateArrays.cs | 102 +++++++++--------- source/includes/method-overloads.rst | 2 +- 2 files changed, 50 insertions(+), 54 deletions(-) diff --git a/source/includes/code-examples/UpdateArrays.cs b/source/includes/code-examples/UpdateArrays.cs index a7cc9bfd..93835b8e 100644 --- a/source/includes/code-examples/UpdateArrays.cs +++ b/source/includes/code-examples/UpdateArrays.cs @@ -14,7 +14,7 @@ public static class UpdateArrays private static string _mongoConnectionString = "mongodb+srv://mikewoofter:mikewoofter@cluster0.pw0q4.mongodb.net/?retryWrites=true&w=majority"; - public static UpdateResult UpdateOneArrayPush() + public static UpdateResult UpdateOnePush() { // start-update-one-push var filter = Builders.Filter @@ -34,7 +34,7 @@ public static UpdateResult UpdateOneArrayPush() // end-update-one-push } - public static async Task UpdateOneArrayPushAsync() + public static async Task UpdateOnePushAsync() { // start-update-one-push-async var filter = Builders.Filter @@ -53,8 +53,47 @@ public static async Task UpdateOneArrayPushAsync() return result; // end-update-one-push-async } + public static UpdateResult UpdateManyPush() + { + // start-update-many-push + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); - public static UpdateResult UpdateOneArrayAddToSet() + var update = Builders.Update + .Push(restaurant => restaurant.Grades, new GradeEntry() + { + Date = DateTime.Now, + Grade = "A", + Score = 96 + }); + + var result = _restaurantsCollection.UpdateMany(filter, update); + + return result; + // end-update-many-push + } + + public static async Task UpdateManyPushAsync() + { + // start-update-many-push-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var update = Builders.Update + .Push(restaurant => restaurant.Grades, new GradeEntry() + { + Date = DateTime.Now, + Grade = "A", + Score = 96 + }); + + var result = await _restaurantsCollection.UpdateManyAsync(filter, update); + + return result; + // end-update-many-push-async + } + + public static UpdateResult UpdateOneAddToSet() { // start-update-one-addtoset var filter = Builders.Filter @@ -71,7 +110,7 @@ public static UpdateResult UpdateOneArrayAddToSet() // end-update-one-addtoset } - public static async Task UpdateOneArrayAddToSetAsync() + public static async Task UpdateOneAddToSetAsync() { // start-update-one-addtoset-async var filter = Builders.Filter @@ -88,7 +127,7 @@ public static async Task UpdateOneArrayAddToSetAsync() // end-update-one-addtoset-async } - public static UpdateResult UpdateManyArrayAddToSet() + public static UpdateResult UpdateManyAddToSet() { // start-update-many-addtoset var filter = Builders.Filter @@ -105,7 +144,7 @@ public static UpdateResult UpdateManyArrayAddToSet() // end-update-many-addtoset } - public static async Task UpdateManyArrayAddToSetAsync() + public static async Task UpdateManyAddToSetAsync() { // start-update-many-addtoset-async var filter = Builders.Filter @@ -122,7 +161,7 @@ public static async Task UpdateManyArrayAddToSetAsync() // end-update-many-addtoset-async } - public static UpdateResult UpdateManyArrayPushEach() + public static UpdateResult UpdateManyPushEach() { // start-update-many-pusheach var filter = Builders.Filter @@ -148,33 +187,7 @@ public static UpdateResult UpdateManyArrayPushEach() // end-update-many-pusheach } - public static UpdateResult UpdateManyArrayPushEach() - { - // start-update-many-pusheach - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); - - var newGrades = new List - { - new GradeEntry { Date = DateTime.Now, Grade = "A", Score = 95 }, - new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89,} - }; - - var scoreSort = Builders.Sort.Descending(g => g.Score); - - var update = Builders.Update.PushEach( - "Grades", - newGrades, - position: 0, - sort: scoreSort); - - var result = _restaurantsCollection.UpdateMany(filter, update); - - return result; - // end-update-many-pusheach - } - - public static async Task UpdateManyArrayPushEachAsync() + public static async Task UpdateManyPushEachAsync() { // start-update-many-pusheach-async var filter = Builders.Filter @@ -191,7 +204,7 @@ public static async Task UpdateManyArrayPushEachAsync() // end-update-many-pusheach-async } - public static UpdateResult UpdateOneArrayPushEach() + public static UpdateResult UpdateOnePushEach() { // start-update-one-pusheach var filter = Builders.Filter @@ -216,7 +229,7 @@ public static UpdateResult UpdateOneArrayPushEach() return result; // end-update-one-pusheach } - public static async Task UpdateOneArrayPushEachAsync() + public static async Task UpdateOnePushEachAsync() { // start-update-one-pusheach-async var filter = Builders.Filter @@ -242,23 +255,6 @@ public static async Task UpdateOneArrayPushEachAsync() // end-update-one-pusheach-async } - public static async Task UpdateOneArrayPushEachAsync() - { - // start-update-one-addtoset-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); - - var firstGradeEntry = _restaurantsCollection.Find(filter).FirstOrDefault().Grades[0]; - - var update = Builders.Update - .AddToSet(restaurant => restaurant.Grades, firstGradeEntry); - - var result = await _restaurantsCollection.UpdateOneAsync(filter, update); - - return result; - // end-update-one-addtoset-async - } - // private static void LinqTest() // { diff --git a/source/includes/method-overloads.rst b/source/includes/method-overloads.rst index d70012f9..a8ef6132 100644 --- a/source/includes/method-overloads.rst +++ b/source/includes/method-overloads.rst @@ -3,4 +3,4 @@ Many of the methods on this page have multiple overloads. The examples in this guide show only one overload for each method. For more information about the available overloads, see the - :manual:`{+new-api-root+} API documentation `. \ No newline at end of file + `API documentation. <{+new-api-root+}/index.html>`__ \ No newline at end of file From adb4e4d169239b6a17e49b427433d2b89d786149 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Thu, 21 Nov 2024 12:22:47 -0600 Subject: [PATCH 14/39] fixes --- source/includes/code-examples/UpdateArrays.cs | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/source/includes/code-examples/UpdateArrays.cs b/source/includes/code-examples/UpdateArrays.cs index 93835b8e..7e125b5d 100644 --- a/source/includes/code-examples/UpdateArrays.cs +++ b/source/includes/code-examples/UpdateArrays.cs @@ -155,7 +155,7 @@ public static async Task UpdateManyAddToSetAsync() var update = Builders.Update .AddToSet(restaurant => restaurant.Grades, firstGradeEntry); - var result = await _restaurantsCollection.UpdateOneAsync(filter, update); + var result = await _restaurantsCollection.UpdateManyAsync(filter, update); return result; // end-update-many-addtoset-async @@ -193,12 +193,21 @@ public static async Task UpdateManyPushEachAsync() var filter = Builders.Filter .Eq("name", "Downtown Deli"); - var firstGradeEntry = _restaurantsCollection.Find(filter).FirstOrDefault().Grades[0]; + var newGrades = new List + { + new GradeEntry { Date = DateTime.Now, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89,} + }; - var update = Builders.Update - .AddToSet(restaurant => restaurant.Grades, firstGradeEntry); + var scoreSort = Builders.Sort.Descending(g => g.Score); - var result = await _restaurantsCollection.UpdateOneAsync(filter, update); + var update = Builders.Update.PushEach( + "Grades", + newGrades, + position: 0, + sort: scoreSort); + + var result = _restaurantsCollection.UpdateManyAsync(filter, update); return result; // end-update-many-pusheach-async From c885e81b058c9a3438e6c9337a33d5128bd51e28 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Fri, 22 Nov 2024 12:32:04 -0600 Subject: [PATCH 15/39] array code examples wip --- .../crud/write-operations/update/arrays.txt | 352 ++++++++++-- .../crud/write-operations/update/fields.txt | 35 +- source/includes/code-examples/UpdateArrays.cs | 530 +++++++++++++++++- 3 files changed, 840 insertions(+), 77 deletions(-) diff --git a/source/fundamentals/crud/write-operations/update/arrays.txt b/source/fundamentals/crud/write-operations/update/arrays.txt index 534ac61d..5f48ac76 100644 --- a/source/fundamentals/crud/write-operations/update/arrays.txt +++ b/source/fundamentals/crud/write-operations/update/arrays.txt @@ -182,6 +182,48 @@ the value already exists in the array, the update operation does nothing. :start-after: // start-update-many-addtoset-async :end-before: // end-update-many-addtoset-async +Add Multiple Values +------------------- + +To add multiple values to an array, call the ``Builders.Update.PushEach()`` method. +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``values`` + - The values to add to the array field. + + **Data Type:** ``IEnumerable`` + + * - ``slice`` + - The number of elements to keep in the array, counted from the start of the array + after updates. If the value is negative, + the method keeps the specified number of elements from the end of the array. + + **Data Type:** ``int?`` + + * - ``position`` + - The position in the array at which to add the values. By default, the method + adds the values to the end of the array. + + **Data Type:** ``int?`` + + * - ``sort`` + - A ``SortDefinition`` object that specifies how the driver sorts the array elements + after adding the new values. + + **Data Type:** `SortDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.SortDefinition-1.html>`__ + The following code example uses the ``PushEach()`` method to add two new ``GradeEntry`` objects to the start of the ``Grades`` array. It then sorts the array elements in descending order by the values of their ``Score`` fields. @@ -228,10 +270,8 @@ descending order by the values of their ``Score`` fields. :start-after: // start-update-many-pusheach-async :end-before: // end-update-many-pusheach-async -Add Multiple Values -------------------- - -To add multiple values to an array, call the ``Builders.Update.PushEach()`` method. +To add multiple values to an array, *but only if they don't already exist in the array*, +call the ``Builders.Update.AddToSetEach()`` method. This method accepts the following parameters: .. list-table:: @@ -251,49 +291,51 @@ This method accepts the following parameters: **Data Type:** ``IEnumerable`` - * - ``slice`` - - The number of elements to keep in the array, counted from the start of the array - after updates. If the value is negative, - the method keeps the specified number of elements from the end of the array. - - **Data Type:** ``int?`` - - * - ``position`` - - The position in the array at which to add the values. By default, the method - adds the values to the end of the array. - - **Data Type:** ``int?`` - - * - ``sort`` - - A ``SortDefinition`` object that specifies how the driver sorts the array elements - after adding the new values. - - **Data Type:** `SortDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.SortDefinition-1.html>`__ +The following code example tries to use the ``AddToSetEach()`` method to re-add the first +and second ``GradeEntry`` objects to the ``Grades`` array in the matching documents. +Because these values already exist in the array, the update operation does nothing. -To add multiple values to an array only if they aren't there, call the -``Builders.Update.AddToSetEach()`` method. This method accepts the following parameters: +.. tabs:: -.. list-table:: - :widths: 30 70 - :header-rows: 1 + .. tab:: UpdateOne (Sync) + :tabid: update-one-addtoseteach-sync - * - Parameter - - Description + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-addtoseteach + :end-before: // end-update-one-addtoseteach - * - ``field`` - - An expression that specifies the array field to add to. + .. tab:: UpdateOne (Async) + :tabid: update-one-addtoseteach-async - **Data Type:** ``Expression>>`` + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-addtoseteach-async + :end-before: // end-update-one-addtoseteach-async - * - ``values`` - - The values to add to the array field. + .. tab:: UpdateMany (Sync) + :tabid: update-many-addtoset-sync - **Data Type:** ``IEnumerable`` + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-addtoseteach + :end-before: // end-update-many-addtoseteach -.. tip:: + .. tab:: UpdateMany (Async) + :tabid: update-many-addtoset-async - If you call the ``AddToSet()`` method with more than one value, the driver automatically - performs the operation as if you called the ``AddToSetEach()`` method. + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-addtoseteach-async + :end-before: // end-update-many-addtoseteach-async Remove Values ------------- @@ -313,6 +355,51 @@ This method accepts the following parameter: **Data Type:** ``Expression>>`` +The following code example uses the ``PopFirst()`` method to remove the first ``GradeEntry`` +object from the ``Grades`` array in the matching documents: + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-popfirst-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-popfirst + :end-before: // end-update-one-popfirst + + .. tab:: UpdateOne (Async) + :tabid: update-one-popfirst-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-popfirst-async + :end-before: // end-update-one-popfirst-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-popfirst-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-popfirst + :end-before: // end-update-many-popfirst + + .. tab:: UpdateMany (Async) + :tabid: update-many-popfirst-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-popfirst-async + :end-before: // end-update-many-popfirst-async + To remove the last value from an array, call the ``Builders.Update.PopLast()`` method: This method accepts the following parameter: @@ -328,6 +415,51 @@ This method accepts the following parameter: **Data Type:** ``Expression>>`` +The following code example uses the ``PopLast()`` method to remove the last ``GradeEntry`` +object from the ``Grades`` array in the matching documents: + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-poplast-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-poplast + :end-before: // end-update-one-poplast + + .. tab:: UpdateOne (Async) + :tabid: update-one-poplast-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-poplast-async + :end-before: // end-update-one-poplast-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-poplast-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-poplast + :end-before: // end-update-many-poplast + + .. tab:: UpdateMany (Async) + :tabid: update-many-poplast-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-poplast-async + :end-before: // end-update-many-poplast-async + To remove all instances of a specific value from an array, call the ``Builders.Update.Pull()`` method: This method accepts the following parameters: @@ -348,7 +480,53 @@ This method accepts the following parameters: **Data Type:** ``IEnumerable`` -To remove all instances of more than one specific value from an array, call the ``Builders.Update.PullAll()`` method: +The following code example uses the ``Pull()`` method to remove all instances of a +a specific ``GradeEntry`` object from the ``Grades`` array in the matching documents: + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-pull-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pull + :end-before: // end-update-one-pull + + .. tab:: UpdateOne (Async) + :tabid: update-one-pull-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pull-async + :end-before: // end-update-one-pull-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-pull-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pull + :end-before: // end-update-many-pull + + .. tab:: UpdateMany (Async) + :tabid: update-many-pull-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pull-async + :end-before: // end-update-many-pull-async + +To remove all instances of more than one specific value from an array, call the +``Builders.Update.PullAll()`` method. This method accepts the following parameters: .. list-table:: @@ -368,7 +546,53 @@ This method accepts the following parameters: **Data Type:** ``IEnumerable`` -To remove all values that match a specific condition from an array, call the ``Builders.Update.PullFilter()`` method: +The following code example uses the ``PullAll()`` method to remove all instances of two +specific ``GradeEntry`` objects from the ``Grades`` array in the matching documents: + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-pullall-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pullall + :end-before: // end-update-one-pullall + + .. tab:: UpdateOne (Async) + :tabid: update-one-pullall-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pullall-async + :end-before: // end-update-one-pullall-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-pullall-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pullall + :end-before: // end-update-many-pullall + + .. tab:: UpdateMany (Async) + :tabid: update-many-pullall-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pullall-async + :end-before: // end-update-many-pullall-async + +To remove all values that match a specific condition from an array, call the +``Builders.Update.PullFilter()`` method. This method accepts the following parameters: .. list-table:: @@ -386,7 +610,53 @@ This method accepts the following parameters: * - ``filter`` - A query filter that specifies the condition for values to remove. - **Data Type:** `FilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ + **Data Type:** `FilterDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ + +The following code example uses the ``PullFilter()`` method to remove all ``GradeEntry`` +objects where the ``Grade`` property is ``"F"`` from the ``Grades`` array in the +matching documents: + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-pullfilter-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pullfilter + :end-before: // end-update-one-pullfilter + + .. tab:: UpdateOne (Async) + :tabid: update-one-pullfilter-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pullfilter-async + :end-before: // end-update-one-pullfilter-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-pullfilter-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pullfilter + :end-before: // end-update-many-pullfilter + + .. tab:: UpdateMany (Async) + :tabid: update-many-pullfilter-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pullfilter-async + :end-before: // end-update-many-pullfilter-async Update Matching Elements ------------------------ diff --git a/source/fundamentals/crud/write-operations/update/fields.txt b/source/fundamentals/crud/write-operations/update/fields.txt index 6f69d411..66369f17 100644 --- a/source/fundamentals/crud/write-operations/update/fields.txt +++ b/source/fundamentals/crud/write-operations/update/fields.txt @@ -277,37 +277,4 @@ method. This method accepts the following parameters: - The format of the date and time, defined in the ``UpdateDefinitionCurrentDateType`` enum. The default value is ``null``. - **Data Type:** `UpdateDefinitionCurrentDateType? <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionCurrentDateType.html>`__ - -The following code example performs these steps: - -1. Creates a query filter that matches documents where the value of the ``name`` field - is "Bagels N Buns". -#. Creates an update definition that sets the value of the ``name`` field to "2 Bagels 2 Buns". -#. Calls the ``UpdateOne()`` method to update the document. - -Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding -code. - -.. tabs:: - - .. tab:: Synchronous - :tabid: update-one-sync - - .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one - :end-before: // end-update-one - - .. tab:: Asynchronous - :tabid: update-one-async - - .. literalinclude:: /includes/code-examples/update-one/UpdateOneAsync.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-async - :end-before: // end-update-one-async - + **Data Type:** `UpdateDefinitionCurrentDateType? <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionCurrentDateType.html>`__ \ No newline at end of file diff --git a/source/includes/code-examples/UpdateArrays.cs b/source/includes/code-examples/UpdateArrays.cs index 7e125b5d..7b47d900 100644 --- a/source/includes/code-examples/UpdateArrays.cs +++ b/source/includes/code-examples/UpdateArrays.cs @@ -53,6 +53,7 @@ public static async Task UpdateOnePushAsync() return result; // end-update-one-push-async } + public static UpdateResult UpdateManyPush() { // start-update-many-push @@ -207,7 +208,7 @@ public static async Task UpdateManyPushEachAsync() position: 0, sort: scoreSort); - var result = _restaurantsCollection.UpdateManyAsync(filter, update); + var result = await _restaurantsCollection.UpdateManyAsync(filter, update); return result; // end-update-many-pusheach-async @@ -238,6 +239,7 @@ public static UpdateResult UpdateOnePushEach() return result; // end-update-one-pusheach } + public static async Task UpdateOnePushEachAsync() { // start-update-one-pusheach-async @@ -258,7 +260,7 @@ public static async Task UpdateOnePushEachAsync() position: 0, sort: scoreSort); - var result = _restaurantsCollection.UpdateOneAsync(filter, update); + var result = await _restaurantsCollection.UpdateOneAsync(filter, update); return result; // end-update-one-pusheach-async @@ -295,4 +297,528 @@ public static void ResetSampleData() _restaurantsCollection.UpdateOne(filter, update); } + + public static UpdateResult UpdateOneAddToSetEach() + { + // start-update-one-addtoseteach + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var doc = _restaurantsCollection.Find(filter).FirstOrDefault(); + var firstGradeEntries = new List { doc.Grades[0], doc.Grades[1] }; + + var update = Builders.Update + .AddToSetEach(restaurant => restaurant.Grades, firstGradeEntries); + + var result = _restaurantsCollection.UpdateOne(filter, update); + + return result; + // end-update-one-addtoseteach + } + + public static async Task UpdateOneAddToSetEachAsync() + { + // start-update-one-addtoseteach-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var doc = _restaurantsCollection.Find(filter).FirstOrDefault(); + var firstGradeEntries = new List { doc.Grades[0], doc.Grades[1] }; + + var update = Builders.Update + .AddToSetEach(restaurant => restaurant.Grades, firstGradeEntries); + + var result = await _restaurantsCollection.UpdateOneAsync(filter, update); + + return result; + // end-update-one-addtoseteach-async + } + + public static UpdateResult UpdateManyAddToSetEach() + { + // start-update-many-addtoseteach + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var doc = _restaurantsCollection.Find(filter).FirstOrDefault(); + var firstGradeEntries = new List { doc.Grades[0], doc.Grades[1] }; + + var update = Builders.Update + .AddToSetEach(restaurant => restaurant.Grades, firstGradeEntries); + + var result = _restaurantsCollection.UpdateMany(filter, update); + + return result; + // end-update-many-addtoseteach + } + + public static async Task UpdateManyAddToSetEachAsync() + { + // start-update-many-addtoseteach-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var doc = _restaurantsCollection.Find(filter).FirstOrDefault(); + var firstGradeEntries = new List { doc.Grades[0], doc.Grades[1] }; + + var update = Builders.Update + .AddToSetEach(restaurant => restaurant.Grades, firstGradeEntries); + + var result = await _restaurantsCollection.UpdateManyAsync(filter, update); + + return result; + // end-update-many-addtoseteach-async + } + + public static UpdateResult UpdateOnePopFirst() + { + // start-update-one-popfirst + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var update = Builders.Update + .PopFirst(restaurant => restaurant.Grades); + + var result = _restaurantsCollection.UpdateOne(filter, update); + + return result; + // end-update-one-popfirst + } + + public static async Task UpdateOnePopFirstAsync() + { + // start-update-one-popfirst-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var update = Builders.Update + .PopFirst(restaurant => restaurant.Grades); + + var result = await _restaurantsCollection.UpdateOneAsync(filter, update); + + return result; + // end-update-one-popfirst-async + } + + public static UpdateResult UpdateManyPopFirst() + { + // start-update-many-popfirst + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var update = Builders.Update + .PopFirst(restaurant => restaurant.Grades); + + var result = _restaurantsCollection.UpdateMany(filter, update); + + return result; + // end-update-many-popfirst + } + + public static async Task UpdateManyPopFirstAsync() + { + // start-update-many-popfirst-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var update = Builders.Update + .PopFirst(restaurant => restaurant.Grades); + + var result = await _restaurantsCollection.UpdateManyAsync(filter, update); + + return result; + // end-update-many-popfirst-async + } + + public static UpdateResult UpdateOnePopLast() + { + // start-update-one-poplast + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var update = Builders.Update + .PopLast(restaurant => restaurant.Grades); + + var result = _restaurantsCollection.UpdateOne(filter, update); + + return result; + // end-update-one-poplast + } + + public static async Task UpdateOnePopLastAsync() + { + // start-update-one-poplast-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var update = Builders.Update + .PopLast(restaurant => restaurant.Grades); + + var result = await _restaurantsCollection.UpdateOneAsync(filter, update); + + return result; + // end-update-one-poplast-async + } + + public static UpdateResult UpdateManyPopLast() + { + // start-update-many-poplast + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var update = Builders.Update + .PopLast(restaurant => restaurant.Grades); + + var result = _restaurantsCollection.UpdateMany(filter, update); + + return result; + // end-update-many-poplast + } + + public static async Task UpdateManyPopLastAsync() + { + // start-update-many-poplast-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var update = Builders.Update + .PopLast(restaurant => restaurant.Grades); + + var result = await _restaurantsCollection.UpdateManyAsync(filter, update); + + return result; + // end-update-many-poplast-async + } + + public static UpdateResult UpdateOnePull() + { + // start-update-one-pull + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Add duplicate values to Grades array + var newGrades = new List + { + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,} + }; + var addUpdate = Builders.Update + .PushEach("Grades", newGrades); + _restaurantsCollection.UpdateOne(filter, addUpdate); + + // Remove duplicates from Grades array + var pullUpdate = Builders.Update + .Pull(restaurant => restaurant.Grades, newGrades[0]); + + var result = _restaurantsCollection.UpdateOne(filter, pullUpdate); + + return result; + // end-update-one-pull + } + + public static async Task UpdateOnePullAsync() + { + // start-update-one-pull-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Add duplicate values to Grades array + var newGrades = new List + { + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,} + }; + var addUpdate = Builders.Update + .PushEach("Grades", newGrades); + await _restaurantsCollection.UpdateOneAsync(filter, addUpdate); + + // Remove duplicates from Grades array + var pullUpdate = Builders.Update + .Pull(restaurant => restaurant.Grades, newGrades[0]); + + var result = await _restaurantsCollection.UpdateOneAsync(filter, pullUpdate); + + return result; + // end-update-one-pull-async + } + + public static UpdateResult UpdateManyPull() + { + // start-update-many-pull + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Add duplicate values to Grades array + var newGrades = new List + { + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,} + }; + var addUpdate = Builders.Update + .PushEach("Grades", newGrades); + _restaurantsCollection.UpdateMany(filter, addUpdate); + + // Remove duplicates from Grades array + var pullUpdate = Builders.Update + .Pull(restaurant => restaurant.Grades, newGrades[0]); + + var result = _restaurantsCollection.UpdateMany(filter, pullUpdate); + + return result; + // end-update-many-pull + } + + public static async Task UpdateManyPullAsync() + { + // start-update-many-pull-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Add duplicate values to Grades array + var newGrades = new List + { + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,} + }; + var addUpdate = Builders.Update + .PushEach("Grades", newGrades); + await _restaurantsCollection.UpdateManyAsync(filter, addUpdate); + + // Remove duplicates from Grades array + var pullUpdate = Builders.Update + .Pull(restaurant => restaurant.Grades, newGrades[0]); + + var result = await _restaurantsCollection.UpdateManyAsync(filter, pullUpdate); + + return result; + // end-update-many-pull-async + } + + public static UpdateResult UpdateOnePullAll() + { + // start-update-one-pullall + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Add duplicate values to Grades array + var newGrades = new List + { + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,}, + new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85,} + }; + var addUpdate = Builders.Update + .PushEach("Grades", newGrades); + _restaurantsCollection.UpdateOne(filter, addUpdate); + + // Remove duplicates from Grades array + var gradesToRemove = new List { newGrades[0], newGrades[2] }; + var pullUpdate = Builders.Update + .PullAll(restaurant => restaurant.Grades, gradesToRemove); + + var result = _restaurantsCollection.UpdateOne(filter, pullUpdate); + + return result; + // end-update-one-pullall + } + + public static async Task UpdateOnePullAllAsync() + { + // start-update-one-pullall-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Add duplicate values to Grades array + var newGrades = new List + { + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,}, + new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85,} + }; + var addUpdate = Builders.Update + .PushEach("Grades", newGrades); + await _restaurantsCollection.UpdateOneAsync(filter, addUpdate); + + // Remove duplicates from Grades array + var gradesToRemove = new List { newGrades[0], newGrades[2] }; + var pullUpdate = Builders.Update + .PullAll(restaurant => restaurant.Grades, gradesToRemove); + + var result = await _restaurantsCollection.UpdateOneAsync(filter, pullUpdate); + + return result; + // end-update-one-pullall-async + } + + public static UpdateResult UpdateManyPullAll() + { + // start-update-many-pullall + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Add duplicate values to Grades array + var newGrades = new List + { + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,}, + new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85,} + }; + var addUpdate = Builders.Update + .PushEach("Grades", newGrades); + _restaurantsCollection.UpdateMany(filter, addUpdate); + + // Remove duplicates from Grades array + var gradesToRemove = new List { newGrades[0], newGrades[2] }; + var pullUpdate = Builders.Update + .PullAll(restaurant => restaurant.Grades, gradesToRemove); + + var result = _restaurantsCollection.UpdateMany(filter, pullUpdate); + + return result; + // end-update-many-pullall + } + + public static async Task UpdateManyPullAllAsync() + { + // start-update-many-pullall-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Add duplicate values to Grades array + var newGrades = new List + { + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,}, + new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85,} + }; + var addUpdate = Builders.Update + .PushEach("Grades", newGrades); + await _restaurantsCollection.UpdateManyAsync(filter, addUpdate); + + // Remove duplicates from Grades array + var gradesToRemove = new List { newGrades[0], newGrades[2] }; + var pullUpdate = Builders.Update + .PullAll(restaurant => restaurant.Grades, gradesToRemove); + + var result = await _restaurantsCollection.UpdateManyAsync(filter, pullUpdate); + + return result; + // end-update-many-pullall-async + } + + public static UpdateResult UpdateOnePullFilter() + { + // start-update-one-pullfilter + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Add GradeEntry values with "Grade = F" to Grades array + var newGrades = new List + { + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 10 }, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 21,}, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 47 }, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 6,} + }; + var addUpdate = Builders.Update + .PushEach("Grades", newGrades); + _restaurantsCollection.UpdateOne(filter, addUpdate); + + // Remove all "Grade = F" values from Grades array + var pullUpdate = Builders.Update + .PullFilter(restaurant => restaurant.Grades, gradeEntry => gradeEntry.Grade == "F"); + + var result = _restaurantsCollection.UpdateOne(filter, pullUpdate); + + return result; + // end-update-one-pullfilter + } + + public static async Task UpdateOnePullFilterAsync() + { + // start-update-one-pullfilter-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Add GradeEntry values with "Grade = F" to Grades array + var newGrades = new List + { + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 10 }, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 21,}, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 47 }, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 6,} + }; + var addUpdate = Builders.Update + .PushEach("Grades", newGrades); + await _restaurantsCollection.UpdateOneAsync(filter, addUpdate); + + // Remove all "Grade = F" values from Grades array + var pullUpdate = Builders.Update + .PullFilter(restaurant => restaurant.Grades, gradeEntry => gradeEntry.Grade == "F"); + + var result = await _restaurantsCollection.UpdateOneAsync(filter, pullUpdate); + + return result; + // end-update-one-pullfilter-async + } + + public static UpdateResult UpdateManyPullFilter() + { + // start-update-many-pullfilter + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Add GradeEntry values with "Grade = F" to Grades array + var newGrades = new List + { + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 10 }, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 21,}, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 47 }, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 6,} + }; + var addUpdate = Builders.Update + .PushEach("Grades", newGrades); + _restaurantsCollection.UpdateMany(filter, addUpdate); + + // Remove all "Grade = F" values from Grades array + var pullUpdate = Builders.Update + .PullFilter(restaurant => restaurant.Grades, gradeEntry => gradeEntry.Grade == "F"); + + var result = _restaurantsCollection.UpdateMany(filter, pullUpdate); + + return result; + // end-update-many-pullfilter + } + + public static async Task UpdateManyPullFilterAsync() + { + // start-update-many-pullfilter-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Add GradeEntry values with "Grade = F" to Grades array + var newGrades = new List + { + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 10 }, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 21,}, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 47 }, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 6,} + }; + var addUpdate = Builders.Update + .PushEach("Grades", newGrades); + await _restaurantsCollection.UpdateManyAsync(filter, addUpdate); + + // Remove all "Grade = F" values from Grades array + var pullUpdate = Builders.Update + .PullFilter(restaurant => restaurant.Grades, gradeEntry => gradeEntry.Grade == "F"); + + var result = await _restaurantsCollection.UpdateManyAsync(filter, pullUpdate); + + return result; + // end-update-many-pullfilter-async + } } \ No newline at end of file From e3ca10ff8dfedb8fcd73e43e0d56bb5e1946f91c Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Fri, 22 Nov 2024 16:40:17 -0600 Subject: [PATCH 16/39] wip --- .../crud/write-operations/update/arrays.txt | 40 ++++++++++++++----- 1 file changed, 31 insertions(+), 9 deletions(-) diff --git a/source/fundamentals/crud/write-operations/update/arrays.txt b/source/fundamentals/crud/write-operations/update/arrays.txt index 5f48ac76..ba40e13f 100644 --- a/source/fundamentals/crud/write-operations/update/arrays.txt +++ b/source/fundamentals/crud/write-operations/update/arrays.txt @@ -658,17 +658,39 @@ matching documents: :start-after: // start-update-many-pullfilter-async :end-before: // end-update-many-pullfilter-async -Update Matching Elements ------------------------- +Update Matching Values +---------------------- -To query and update specific elements in an array field, use -the :manual:`positional operator ` (``$``) -when you specify the field to update. -Combined with the ``Builders.Update.Set()`` method, you can use this operator to query -and update specific elements in an array field. +To update a value in an array field, call the ``Builders.Update.Set()`` method. +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to update. -To update the first array element that matches your query filter, use the -positional ``$`` operator. The array value must appear be part of the query filter. + **Data Type:** ``Expression>>`` + + * - ``value`` + - The new value to set in the array field. + + **Data Type:** ``TItem`` + +You can use the +:manual:`positional operator ` (``$``) +to query and update specific values in the array. + +.. note:: The array field must be part of the query filter. + +The following code example uses the ``Set()`` method and the positional operator to +update remove all ``GradeEntry`` +objects where the ``Grade`` property is ``"F"`` from the ``Grades`` array in the +matching documents: The following code example queries the ``restaurants`` collection for a document that contains a grade of 2. It then updates that grade to 22 in the matching documents. From 7d8e98d6d57c826f827c715d115fe938020438b4 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Mon, 25 Nov 2024 16:44:37 -0600 Subject: [PATCH 17/39] starting template --- snooty.toml | 3 +- .../{update.txt => update-many.txt} | 0 .../{update => update-many}/arrays.txt | 179 +++- .../{update => update-many}/fields.txt | 0 .../crud/write-operations/update-one.txt | 51 + .../write-operations/update-one/arrays.txt | 899 ++++++++++++++++++ .../write-operations/update-one/fields.txt | 280 ++++++ .../code-examples/UpdateManyArrays.cs | 534 +++++++++++ .../{UpdateArrays.cs => UpdateOneArrays.cs} | 509 +++------- source/includes/page-templates/update.rst | 316 ++++++ 10 files changed, 2351 insertions(+), 420 deletions(-) rename source/fundamentals/crud/write-operations/{update.txt => update-many.txt} (100%) rename source/fundamentals/crud/write-operations/{update => update-many}/arrays.txt (79%) rename source/fundamentals/crud/write-operations/{update => update-many}/fields.txt (100%) create mode 100644 source/fundamentals/crud/write-operations/update-one.txt create mode 100644 source/fundamentals/crud/write-operations/update-one/arrays.txt create mode 100644 source/fundamentals/crud/write-operations/update-one/fields.txt create mode 100644 source/includes/code-examples/UpdateManyArrays.cs rename source/includes/code-examples/{UpdateArrays.cs => UpdateOneArrays.cs} (53%) create mode 100644 source/includes/page-templates/update.rst diff --git a/snooty.toml b/snooty.toml index 6d7028cf..33245484 100644 --- a/snooty.toml +++ b/snooty.toml @@ -4,7 +4,8 @@ toc_landing_pages = [ "/usage-examples", "/fundamentals", "/fundamentals/serialization", - "/fundamentals/crud/write-operations/update", + "/fundamentals/crud/write-operations/update-one", + "/fundamentals/crud/write-operations/update-many", "/upgrade", ] name = "csharp" diff --git a/source/fundamentals/crud/write-operations/update.txt b/source/fundamentals/crud/write-operations/update-many.txt similarity index 100% rename from source/fundamentals/crud/write-operations/update.txt rename to source/fundamentals/crud/write-operations/update-many.txt diff --git a/source/fundamentals/crud/write-operations/update/arrays.txt b/source/fundamentals/crud/write-operations/update-many/arrays.txt similarity index 79% rename from source/fundamentals/crud/write-operations/update/arrays.txt rename to source/fundamentals/crud/write-operations/update-many/arrays.txt index ba40e13f..27cefdb5 100644 --- a/source/fundamentals/crud/write-operations/update/arrays.txt +++ b/source/fundamentals/crud/write-operations/update-many/arrays.txt @@ -682,32 +682,173 @@ This method accepts the following parameters: **Data Type:** ``TItem`` You can use the -:manual:`positional operator ` (``$``) -to query and update specific values in the array. +:manual:`positional operator ` +in combination with the ``Set()`` method to query and update specific values in the array. +The following sections describe different ways to use the positional operator. -.. note:: The array field must be part of the query filter. +First Matching Value +~~~~~~~~~~~~~~~~~~~~ -The following code example uses the ``Set()`` method and the positional operator to -update remove all ``GradeEntry`` -objects where the ``Grade`` property is ``"F"`` from the ``Grades`` array in the -matching documents: +To update only the first value in an array that matches a query filter, use the positional operator +(``$``) in combination with the ``Set()`` method. + +.. note:: + + To use the positional operator, the array field must be part of the query filter. -The following code example queries the ``restaurants`` collection for a document -that contains a grade of 2. It then updates that grade to 22 in the matching documents. -Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding code. +The following example uses the ``Set()`` method and the positional operator to +update the ``Grades`` array in all documents that match the query filter. First, +it finds *only the first* ``GradeEntry`` object in the ``Grades`` array where the ``Grade`` property +has the value ``"A"``. Then, it updates the ``Score`` property of the first matching +``GradeEntry`` object to 100. -To update all array elements in the matching documents, use the all positional operator -(``$[]``). +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-positional-sync -The following code example queries the ``restaurants`` collection for a document -where the ``name`` is ``"Downtown Deli"``. It then updates all that grade to 22 in the matching documents. -Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding code. + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-positional + :end-before: // end-update-one-positional + + .. tab:: UpdateOne (Async) + :tabid: update-one-positional-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-positional-async + :end-before: // end-update-one-positional-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-positional-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-positional + :end-before: // end-update-many-positional -To update all array elements that match your query filter, use the all positional operator -(``$[]``). The array value must appear be part of the query filter. + .. tab:: UpdateMany (Async) + :tabid: update-many-positional-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-positional-async + :end-before: // end-update-many-positional-async + +All Matching Values +~~~~~~~~~~~~~~~~~~~ + +To update all values in an array that match a specified condition, use the filtered +positional operator (``$[]``) in combination with the ``Set()`` method. + +The following example uses the ``Set()`` method and the filtered positional operator +to update the ``Score`` property of all matching +``GradeEntry`` objects in the Grades`` array to 100 in all documents that match the +query filter. + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-allpositional-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-allpositional + :end-before: // end-update-one-allpositional + + .. tab:: UpdateOne (Async) + :tabid: update-one-allpositional-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-allpositional-async + :end-before: // end-update-one-allpositional-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-allpositional-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-allpositional + :end-before: // end-update-many-allpositional + + .. tab:: UpdateMany (Async) + :tabid: update-many-allpositional-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-allpositional-async + :end-before: // end-update-many-allpositional-async + +All Values +~~~~~~~~~~ + +To update all values in an array that match a query filter, use the all-positional operator +(``$[]``) in combination with the ``Set()`` method. + +The following example uses the ``Set()`` method and the all-positional operator +to update the ``Score`` property of all ``GradeEntry`` objects in the Grades`` array +to 100 in all documents that match the query filter. + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-filteredpositional-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-filteredpositional + :end-before: // end-update-one-filteredpositional + + .. tab:: UpdateOne (Async) + :tabid: update-one-filteredpositional-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-filteredpositional-async + :end-before: // end-update-one-filteredpositional-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-filteredpositional-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-filteredpositional + :end-before: // end-update-many-filteredpositional + + .. tab:: UpdateMany (Async) + :tabid: update-many-filteredpositional-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-filteredpositional-async + :end-before: // end-update-many-filteredpositional-async -The following code example queries the ``restaurants`` collection for a document -that contains a grade of 2. It then updates that grade to 22 in the matching documents. LINQ3 Provider ~~~~~~~~~~~~~~ diff --git a/source/fundamentals/crud/write-operations/update/fields.txt b/source/fundamentals/crud/write-operations/update-many/fields.txt similarity index 100% rename from source/fundamentals/crud/write-operations/update/fields.txt rename to source/fundamentals/crud/write-operations/update-many/fields.txt diff --git a/source/fundamentals/crud/write-operations/update-one.txt b/source/fundamentals/crud/write-operations/update-one.txt new file mode 100644 index 00000000..d089e48e --- /dev/null +++ b/source/fundamentals/crud/write-operations/update-one.txt @@ -0,0 +1,51 @@ +.. _csharp-change-guide: +.. _csharp-update-documents: + +========== +Update One +========== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: synchronous, asynchronous + +.. toctree:: + :caption: Update Documents + + Fields + Arrays + +.. include:: /includes/page-templates/update.rst + + .. replacement:: sync-method + + UpdateOne + + .. replacement:: async-method + + UpdateOneAsync + + .. replacement:: document-or-documents + + document + + .. replacement:: tab-id + + update-one + + .. replacement:: single-or-multiple + + a single document + + .. replacement:: one-or-many + + one \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations/update-one/arrays.txt b/source/fundamentals/crud/write-operations/update-one/arrays.txt new file mode 100644 index 00000000..27cefdb5 --- /dev/null +++ b/source/fundamentals/crud/write-operations/update-one/arrays.txt @@ -0,0 +1,899 @@ +.. _csharp-update-arrays: + +============= +Update Arrays +============= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: synchronous, asynchronous + +Overview +-------- + +On this page, you can learn how to create ``UpdateDefinition`` objects for array fields. +An ``UpdateDefinition`` object specifies the kind of update operation to perform, the +fields to update, and the new value for each field, if applicable. + +The {+driver-short+} supports the array update operators and modifiers described in the +:manual:`{+mdb-server+} manual `. +To create an ``UpdateDefinition`` object for one of these operators, call the corresponding +method from the ``Builders.Update`` property. +The following sections describe these methods in more detail. + +After you create an ``UpdateDefinition``, pass it to one of the update methods +described on the :ref:`` page. + +.. include:: /includes/method-overloads.rst + +.. include:: /includes/atlas-sample-data.rst + +Add One Value +------------- + +To add one value to the end of an array, call the ``Builders.Update.Push()`` method. +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add a value to. + + **Data Type:** ``Expression>>`` + + * - ``value`` + - The value to add to the end of the array field. + + **Data Type:** ``TItem`` + +The following code example uses the ``Push()`` method to add a new ``GradeEntry`` object +to the ``Grades`` array in the matching documents: + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-push-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-push + :end-before: // end-update-one-push + + .. tab:: UpdateOne (Async) + :tabid: update-one-push-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-push-async + :end-before: // end-update-one-push-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-push-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-push + :end-before: // end-update-many-push + + .. tab:: UpdateMany (Async) + :tabid: update-many-push-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-push-async + :end-before: // end-update-many-push-async + +.. tip:: Configure the Push Operation + + To add a value at a specific position in an array, or to sort or slice the array after + updating it, call the ``PushEach()`` method instead. + TODO: link this + +To add one value to the end of an array, *but only if it doesn't already exist in the array*, +call the ``Builders.Update.AddToSet()`` method. +{+mdb-server+} determines whether the value already exists in the array by +comparing the value's BSON representation to the BSON representation of each +other element in the array. + +The ``AddToSet()`` method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``value`` + - The value to add to the end of the array field. + + **Data Type:** ``TItem`` + +The following code example tries to use the ``AddToSet()`` method to re-add the first +``GradeEntry`` object to the ``Grades`` array in the matching documents. Because +the value already exists in the array, the update operation does nothing. + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-addtoset-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-addtoset + :end-before: // end-update-one-addtoset + + .. tab:: UpdateOne (Async) + :tabid: update-one-addtoset-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-addtoset-async + :end-before: // end-update-one-addtoset-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-addtoset-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-addtoset + :end-before: // end-update-many-addtoset + + .. tab:: UpdateMany (Async) + :tabid: update-many-addtoset-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-addtoset-async + :end-before: // end-update-many-addtoset-async + +Add Multiple Values +------------------- + +To add multiple values to an array, call the ``Builders.Update.PushEach()`` method. +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``values`` + - The values to add to the array field. + + **Data Type:** ``IEnumerable`` + + * - ``slice`` + - The number of elements to keep in the array, counted from the start of the array + after updates. If the value is negative, + the method keeps the specified number of elements from the end of the array. + + **Data Type:** ``int?`` + + * - ``position`` + - The position in the array at which to add the values. By default, the method + adds the values to the end of the array. + + **Data Type:** ``int?`` + + * - ``sort`` + - A ``SortDefinition`` object that specifies how the driver sorts the array elements + after adding the new values. + + **Data Type:** `SortDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.SortDefinition-1.html>`__ + +The following code example uses the ``PushEach()`` method to add two new ``GradeEntry`` +objects to the start of the ``Grades`` array. It then sorts the array elements in +descending order by the values of their ``Score`` fields. + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-pusheach-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pusheach + :end-before: // end-update-one-pusheach + + .. tab:: UpdateOne (Async) + :tabid: update-one-pusheach-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pusheach-async + :end-before: // end-update-one-pusheach-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-pusheach-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pusheach + :end-before: // end-update-many-pusheach + + .. tab:: UpdateMany (Async) + :tabid: update-many-pusheach-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pusheach-async + :end-before: // end-update-many-pusheach-async + +To add multiple values to an array, *but only if they don't already exist in the array*, +call the ``Builders.Update.AddToSetEach()`` method. +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``values`` + - The values to add to the array field. + + **Data Type:** ``IEnumerable`` + +The following code example tries to use the ``AddToSetEach()`` method to re-add the first +and second ``GradeEntry`` objects to the ``Grades`` array in the matching documents. +Because these values already exist in the array, the update operation does nothing. + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-addtoseteach-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-addtoseteach + :end-before: // end-update-one-addtoseteach + + .. tab:: UpdateOne (Async) + :tabid: update-one-addtoseteach-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-addtoseteach-async + :end-before: // end-update-one-addtoseteach-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-addtoset-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-addtoseteach + :end-before: // end-update-many-addtoseteach + + .. tab:: UpdateMany (Async) + :tabid: update-many-addtoset-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-addtoseteach-async + :end-before: // end-update-many-addtoseteach-async + +Remove Values +------------- + +To remove the first value from an array, call the ``Builders.Update.PopFirst()`` method. +This method accepts the following parameter: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to remove the first value from. + + **Data Type:** ``Expression>>`` + +The following code example uses the ``PopFirst()`` method to remove the first ``GradeEntry`` +object from the ``Grades`` array in the matching documents: + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-popfirst-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-popfirst + :end-before: // end-update-one-popfirst + + .. tab:: UpdateOne (Async) + :tabid: update-one-popfirst-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-popfirst-async + :end-before: // end-update-one-popfirst-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-popfirst-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-popfirst + :end-before: // end-update-many-popfirst + + .. tab:: UpdateMany (Async) + :tabid: update-many-popfirst-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-popfirst-async + :end-before: // end-update-many-popfirst-async + +To remove the last value from an array, call the ``Builders.Update.PopLast()`` method: +This method accepts the following parameter: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to remove the last value from. + + **Data Type:** ``Expression>>`` + +The following code example uses the ``PopLast()`` method to remove the last ``GradeEntry`` +object from the ``Grades`` array in the matching documents: + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-poplast-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-poplast + :end-before: // end-update-one-poplast + + .. tab:: UpdateOne (Async) + :tabid: update-one-poplast-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-poplast-async + :end-before: // end-update-one-poplast-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-poplast-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-poplast + :end-before: // end-update-many-poplast + + .. tab:: UpdateMany (Async) + :tabid: update-many-poplast-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-poplast-async + :end-before: // end-update-many-poplast-async + +To remove all instances of a specific value from an array, call the ``Builders.Update.Pull()`` method: +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``value`` + - The value to remove from the array field. + + **Data Type:** ``IEnumerable`` + +The following code example uses the ``Pull()`` method to remove all instances of a +a specific ``GradeEntry`` object from the ``Grades`` array in the matching documents: + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-pull-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pull + :end-before: // end-update-one-pull + + .. tab:: UpdateOne (Async) + :tabid: update-one-pull-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pull-async + :end-before: // end-update-one-pull-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-pull-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pull + :end-before: // end-update-many-pull + + .. tab:: UpdateMany (Async) + :tabid: update-many-pull-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pull-async + :end-before: // end-update-many-pull-async + +To remove all instances of more than one specific value from an array, call the +``Builders.Update.PullAll()`` method. +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``values`` + - The values to remove from the array field. + + **Data Type:** ``IEnumerable`` + +The following code example uses the ``PullAll()`` method to remove all instances of two +specific ``GradeEntry`` objects from the ``Grades`` array in the matching documents: + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-pullall-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pullall + :end-before: // end-update-one-pullall + + .. tab:: UpdateOne (Async) + :tabid: update-one-pullall-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pullall-async + :end-before: // end-update-one-pullall-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-pullall-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pullall + :end-before: // end-update-many-pullall + + .. tab:: UpdateMany (Async) + :tabid: update-many-pullall-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pullall-async + :end-before: // end-update-many-pullall-async + +To remove all values that match a specific condition from an array, call the +``Builders.Update.PullFilter()`` method. +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``filter`` + - A query filter that specifies the condition for values to remove. + + **Data Type:** `FilterDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ + +The following code example uses the ``PullFilter()`` method to remove all ``GradeEntry`` +objects where the ``Grade`` property is ``"F"`` from the ``Grades`` array in the +matching documents: + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-pullfilter-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pullfilter + :end-before: // end-update-one-pullfilter + + .. tab:: UpdateOne (Async) + :tabid: update-one-pullfilter-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pullfilter-async + :end-before: // end-update-one-pullfilter-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-pullfilter-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pullfilter + :end-before: // end-update-many-pullfilter + + .. tab:: UpdateMany (Async) + :tabid: update-many-pullfilter-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pullfilter-async + :end-before: // end-update-many-pullfilter-async + +Update Matching Values +---------------------- + +To update a value in an array field, call the ``Builders.Update.Set()`` method. +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to update. + + **Data Type:** ``Expression>>`` + + * - ``value`` + - The new value to set in the array field. + + **Data Type:** ``TItem`` + +You can use the +:manual:`positional operator ` +in combination with the ``Set()`` method to query and update specific values in the array. +The following sections describe different ways to use the positional operator. + +First Matching Value +~~~~~~~~~~~~~~~~~~~~ + +To update only the first value in an array that matches a query filter, use the positional operator +(``$``) in combination with the ``Set()`` method. + +.. note:: + + To use the positional operator, the array field must be part of the query filter. + +The following example uses the ``Set()`` method and the positional operator to +update the ``Grades`` array in all documents that match the query filter. First, +it finds *only the first* ``GradeEntry`` object in the ``Grades`` array where the ``Grade`` property +has the value ``"A"``. Then, it updates the ``Score`` property of the first matching +``GradeEntry`` object to 100. + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-positional-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-positional + :end-before: // end-update-one-positional + + .. tab:: UpdateOne (Async) + :tabid: update-one-positional-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-positional-async + :end-before: // end-update-one-positional-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-positional-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-positional + :end-before: // end-update-many-positional + + .. tab:: UpdateMany (Async) + :tabid: update-many-positional-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-positional-async + :end-before: // end-update-many-positional-async + +All Matching Values +~~~~~~~~~~~~~~~~~~~ + +To update all values in an array that match a specified condition, use the filtered +positional operator (``$[]``) in combination with the ``Set()`` method. + +The following example uses the ``Set()`` method and the filtered positional operator +to update the ``Score`` property of all matching +``GradeEntry`` objects in the Grades`` array to 100 in all documents that match the +query filter. + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-allpositional-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-allpositional + :end-before: // end-update-one-allpositional + + .. tab:: UpdateOne (Async) + :tabid: update-one-allpositional-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-allpositional-async + :end-before: // end-update-one-allpositional-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-allpositional-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-allpositional + :end-before: // end-update-many-allpositional + + .. tab:: UpdateMany (Async) + :tabid: update-many-allpositional-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-allpositional-async + :end-before: // end-update-many-allpositional-async + +All Values +~~~~~~~~~~ + +To update all values in an array that match a query filter, use the all-positional operator +(``$[]``) in combination with the ``Set()`` method. + +The following example uses the ``Set()`` method and the all-positional operator +to update the ``Score`` property of all ``GradeEntry`` objects in the Grades`` array +to 100 in all documents that match the query filter. + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-filteredpositional-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-filteredpositional + :end-before: // end-update-one-filteredpositional + + .. tab:: UpdateOne (Async) + :tabid: update-one-filteredpositional-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-filteredpositional-async + :end-before: // end-update-one-filteredpositional-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-filteredpositional-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-filteredpositional + :end-before: // end-update-many-filteredpositional + + .. tab:: UpdateMany (Async) + :tabid: update-many-filteredpositional-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-filteredpositional-async + :end-before: // end-update-many-filteredpositional-async + + +LINQ3 Provider +~~~~~~~~~~~~~~ + +LINQ syntax contains a positional operator (``$``) that you can use to update elements in an array field. +Previous versions of the {+driver-short+} supported both the LINQ2 and LINQ3 providers. +In LINQ2, you could use ``-1`` to indicate use of the positional operator. + +For example, the ``Restaurant`` class contains an array field named ``Grades`` that +contains multiple ``GradeEntry`` elements. If your application were using the LINQ2 +provider, you could use the following code sample to update the +``Grade`` field of the first element in this array: + +.. code-block:: csharp + :linenos: + + var anArrayId = ObjectId.GenerateNewId(); + var another = new Restaurant + { + Id = ObjectId.GenerateNewId(), + AnArrayMember = new List + { + new AnArrayClass { Id = anArrayId, Deleted = false } + } + }; + + await collection.UpdateOneAsync( + r => r.Id == "targetId" && r.AnArrayMember.Any(l => l.Id == anArrayId), + Builders.Update.Set(l => l.AnArrayMember.ElementAt(-1).Deleted, true)); + +.. code-block:: csharp + :linenos: + + var anArrayId = ObjectId.GenerateNewId(); + var another = new Restaurant + { + Id = ObjectId.GenerateNewId(), + AnArrayMember = new List + { + new AnArrayClass { Id = anArrayId, Deleted = false } + } + }; + + await collection.UpdateOneAsync( + r => r.Id == "targetId" && r.AnArrayMember.Any(l => l.Id == anArrayId), + Builders.Update.Set(l => l.AnArrayMember.ElementAt(-1).Deleted, true)); + +This no longer works in LINQ3. Instead, you must use the following syntax: diff --git a/source/fundamentals/crud/write-operations/update-one/fields.txt b/source/fundamentals/crud/write-operations/update-one/fields.txt new file mode 100644 index 00000000..66369f17 --- /dev/null +++ b/source/fundamentals/crud/write-operations/update-one/fields.txt @@ -0,0 +1,280 @@ +.. _csharp-update-fields: + +============= +Update Fields +============= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: synchronous, asynchronous + +Overview +-------- + +On this page, you can learn how to use the {+driver-long+} to update +fields in MongoDB documents. This page describes how to create ``UpdateDefinition`` +objects that specify the update operations you want to perform on fields. +You can pass these objects to the update methods described on the +:ref:`` page. + +The {+driver-short+} supports the field update operators described in the +:manual:`{+mdb-server+} manual `. To specify an +update operation, call the corresponding method from the ``Builders.Update`` property. +The following sections describe these methods in more detail. + +.. tip:: Interactive Lab + + This page includes a short interactive lab that demonstrates how to + modify data by using the ``UpdateManyAsync()`` method. You can complete this + lab directly in your browser window without installing MongoDB or a code editor. + + To start the lab, click the :guilabel:`Open Interactive Tutorial` button at the + top of the page. To expand the lab to a full-screen format, click the + full-screen button (:guilabel:`â›¶`) in the top-right corner of the lab pane. + +.. note:: Method Overloads + + Many of the methods in this guide have multiple overloads. The examples + in this guide use the simplest overload for demonstration purposes. For + more information about the available overloads, see the + :manual:`{+new-api-root+} API documentation `. + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``restaurants`` collection +from the ``sample_restaurants`` database. The documents in this +collection use the following ``Restaurant``, ``Address``, and ``GradeEntry`` +classes as models: + +.. literalinclude:: /includes/code-examples/Restaurant.cs + :language: csharp + :copyable: + :dedent: + +.. literalinclude:: /includes/code-examples/Address.cs + :language: csharp + :copyable: + :dedent: + +.. literalinclude:: /includes/code-examples/GradeEntry.cs + :language: csharp + :copyable: + :dedent: + +.. include:: /includes/convention-pack-note.rst + +This collection is from the :atlas:`sample datasets ` provided +by Atlas. See the :ref:`` to learn how to create a free MongoDB cluster +and load this sample data. + +.. _csharp-update-operation: + +Increment a Value +----------------- + +To increment the value of a field by a specific amount, call the ``Builders.Update.Inc()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to increment. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The amount to increment the field by. + + **Data Type:** ``TField`` + +Set If Lower or Greater +----------------------- + +To update the value of the field to a specified value, *but only if the specified value +is greater than the current value of the field,* call the ``Builders.Update.Max()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The value to set the field to. + + **Data Type:** ``TField`` + +To update the value of the field to a specified value, *but only if the specified value +is lesser than the current value of the field,* call the ``Builders.Update.Min()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The value to set the field to. + + **Data Type:** ``TField`` + +Multiply a Value +--------------- + +To multiply the value of a field by a specific amount, call the ``Builders.Update.Mul()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The amount to multiply the field by. + + **Data Type:** ``TField`` + +Rename a Field +-------------- + +To rename a field, call the ``Builders.Update.Rename()`` method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to rename. + + **Data Type:** ``Expression>`` + + * - ``newName`` + - The new name for the field. + + **Data Type:** ``string`` + +Set a Value +----------- + +To set the value of a field to a specific value, call the ``Builders.Update.Set()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The value to set the field to. + + **Data Type:** ``TField`` + +Unset a Field +------------- + +To remove a field from a document, call the ``Builders.Update.Unset()`` method. This method accepts the following parameter: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to remove. + + **Data Type:** ``Expression>`` + +Set on Insert +------------- + +To set the value of a field only if the document is an upsert, call the ``Builders.Update.SetOnInsert()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The value to set the field to. + + **Data Type:** ``TField`` + +Set the Current Date +-------------------- + +To set the value of a field to the current date and time, call the ``Builders.Update.CurrentDate()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``type`` + - The format of the date and time, defined in the ``UpdateDefinitionCurrentDateType`` + enum. The default value is ``null``. + + **Data Type:** `UpdateDefinitionCurrentDateType? <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionCurrentDateType.html>`__ \ No newline at end of file diff --git a/source/includes/code-examples/UpdateManyArrays.cs b/source/includes/code-examples/UpdateManyArrays.cs new file mode 100644 index 00000000..872e56cc --- /dev/null +++ b/source/includes/code-examples/UpdateManyArrays.cs @@ -0,0 +1,534 @@ +using MongoDB.Bson; +using MongoDB.Bson.Serialization.Conventions; +using MongoDB.Driver; +using WriteData.Models; + +namespace CSharpExamples.WriteData; + +public class UpdateManyArrays +{ + private static IMongoCollection _restaurantsCollection; + //private static string _mongoConnectionString = ""; + private static string _mongoConnectionString = + "mongodb+srv://mikewoofter:mikewoofter@cluster0.pw0q4.mongodb.net/?retryWrites=true&w=majority"; + + public static void Setup() + { + // This allows automapping of the camelCase database fields to our models. + var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; + ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); + + // Establish the connection to MongoDB and get the restaurants database + var mongoClient = new MongoClient(_mongoConnectionString); + var restaurantsDatabase = mongoClient.GetDatabase("sample_restaurants"); + _restaurantsCollection = restaurantsDatabase.GetCollection("restaurants"); + } + + public static UpdateResult UpdateManyPush() + { + // start-update-many-push + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var update = Builders.Update + .Push(restaurant => restaurant.Grades, new GradeEntry() + { + Date = DateTime.Now, + Grade = "A", + Score = 96 + }); + + var result = _restaurantsCollection.UpdateMany(filter, update); + + return result; + // end-update-many-push + } + + public static async Task UpdateManyPushAsync() + { + // start-update-many-push-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var update = Builders.Update + .Push(restaurant => restaurant.Grades, new GradeEntry() + { + Date = DateTime.Now, + Grade = "A", + Score = 96 + }); + + var result = await _restaurantsCollection.UpdateManyAsync(filter, update); + + return result; + // end-update-many-push-async + } + + public static UpdateResult UpdateManyAddToSet() + { + // start-update-many-addtoset + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var firstGradeEntry = _restaurantsCollection.Find(filter).FirstOrDefault().Grades[0]; + + var update = Builders.Update + .AddToSet(restaurant => restaurant.Grades, firstGradeEntry); + + var result = _restaurantsCollection.UpdateMany(filter, update); + + return result; + // end-update-many-addtoset + } + + public static async Task UpdateManyAddToSetAsync() + { + // start-update-many-addtoset-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var firstGradeEntry = _restaurantsCollection.Find(filter).FirstOrDefault().Grades[0]; + + var update = Builders.Update + .AddToSet(restaurant => restaurant.Grades, firstGradeEntry); + + var result = await _restaurantsCollection.UpdateManyAsync(filter, update); + + return result; + // end-update-many-addtoset-async + } + + public static UpdateResult UpdateManyPushEach() + { + // start-update-many-pusheach + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var newGrades = new List + { + new GradeEntry { Date = DateTime.Now, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89,} + }; + + var scoreSort = Builders.Sort.Descending(g => g.Score); + + var update = Builders.Update.PushEach( + "Grades", + newGrades, + position: 0, + sort: scoreSort); + + var result = _restaurantsCollection.UpdateMany(filter, update); + + return result; + // end-update-many-pusheach + } + + public static async Task UpdateManyPushEachAsync() + { + // start-update-many-pusheach-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var newGrades = new List + { + new GradeEntry { Date = DateTime.Now, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89,} + }; + + var scoreSort = Builders.Sort.Descending(g => g.Score); + + var update = Builders.Update.PushEach( + "Grades", + newGrades, + position: 0, + sort: scoreSort); + + var result = await _restaurantsCollection.UpdateManyAsync(filter, update); + + return result; + // end-update-many-pusheach-async + } + + public static UpdateResult UpdateManyAddToSetEach() + { + // start-update-many-addtoseteach + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var doc = _restaurantsCollection.Find(filter).FirstOrDefault(); + var firstGradeEntries = new List { doc.Grades[0], doc.Grades[1] }; + + var update = Builders.Update + .AddToSetEach(restaurant => restaurant.Grades, firstGradeEntries); + + var result = _restaurantsCollection.UpdateMany(filter, update); + + return result; + // end-update-many-addtoseteach + } + + public static async Task UpdateManyAddToSetEachAsync() + { + // start-update-many-addtoseteach-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var doc = _restaurantsCollection.Find(filter).FirstOrDefault(); + var firstGradeEntries = new List { doc.Grades[0], doc.Grades[1] }; + + var update = Builders.Update + .AddToSetEach(restaurant => restaurant.Grades, firstGradeEntries); + + var result = await _restaurantsCollection.UpdateManyAsync(filter, update); + + return result; + // end-update-many-addtoseteach-async + } + + public static UpdateResult UpdateManyPopFirst() + { + // start-update-many-popfirst + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var update = Builders.Update + .PopFirst(restaurant => restaurant.Grades); + + var result = _restaurantsCollection.UpdateMany(filter, update); + + return result; + // end-update-many-popfirst + } + + public static async Task UpdateManyPopFirstAsync() + { + // start-update-many-popfirst-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var update = Builders.Update + .PopFirst(restaurant => restaurant.Grades); + + var result = await _restaurantsCollection.UpdateManyAsync(filter, update); + + return result; + // end-update-many-popfirst-async + } + + public static UpdateResult UpdateManyPopLast() + { + // start-update-many-poplast + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var update = Builders.Update + .PopLast(restaurant => restaurant.Grades); + + var result = _restaurantsCollection.UpdateMany(filter, update); + + return result; + // end-update-many-poplast + } + + public static async Task UpdateManyPopLastAsync() + { + // start-update-many-poplast-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var update = Builders.Update + .PopLast(restaurant => restaurant.Grades); + + var result = await _restaurantsCollection.UpdateManyAsync(filter, update); + + return result; + // end-update-many-poplast-async + } + + public static UpdateResult UpdateManyPull() + { + // start-update-many-pull + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Add duplicate values to Grades array + var newGrades = new List + { + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,} + }; + var addUpdate = Builders.Update + .PushEach("Grades", newGrades); + _restaurantsCollection.UpdateMany(filter, addUpdate); + + // Remove duplicates from Grades array + var pullUpdate = Builders.Update + .Pull(restaurant => restaurant.Grades, newGrades[0]); + + var result = _restaurantsCollection.UpdateMany(filter, pullUpdate); + + return result; + // end-update-many-pull + } + + public static async Task UpdateManyPullAsync() + { + // start-update-many-pull-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Add duplicate values to Grades array + var newGrades = new List + { + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,} + }; + var addUpdate = Builders.Update + .PushEach("Grades", newGrades); + await _restaurantsCollection.UpdateManyAsync(filter, addUpdate); + + // Remove duplicates from Grades array + var pullUpdate = Builders.Update + .Pull(restaurant => restaurant.Grades, newGrades[0]); + + var result = await _restaurantsCollection.UpdateManyAsync(filter, pullUpdate); + + return result; + // end-update-many-pull-async + } + + public static UpdateResult UpdateManyPullAll() + { + // start-update-many-pullall + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Add duplicate values to Grades array + var newGrades = new List + { + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,}, + new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85,} + }; + var addUpdate = Builders.Update + .PushEach("Grades", newGrades); + _restaurantsCollection.UpdateMany(filter, addUpdate); + + // Remove duplicates from Grades array + var gradesToRemove = new List { newGrades[0], newGrades[2] }; + var pullUpdate = Builders.Update + .PullAll(restaurant => restaurant.Grades, gradesToRemove); + + var result = _restaurantsCollection.UpdateMany(filter, pullUpdate); + + return result; + // end-update-many-pullall + } + + public static async Task UpdateManyPullAllAsync() + { + // start-update-many-pullall-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Add duplicate values to Grades array + var newGrades = new List + { + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,}, + new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85,} + }; + var addUpdate = Builders.Update + .PushEach("Grades", newGrades); + await _restaurantsCollection.UpdateManyAsync(filter, addUpdate); + + // Remove duplicates from Grades array + var gradesToRemove = new List { newGrades[0], newGrades[2] }; + var pullUpdate = Builders.Update + .PullAll(restaurant => restaurant.Grades, gradesToRemove); + + var result = await _restaurantsCollection.UpdateManyAsync(filter, pullUpdate); + + return result; + // end-update-many-pullall-async + } + + public static UpdateResult UpdateManyPullFilter() + { + // start-update-many-pullfilter + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Add GradeEntry values with "Grade = F" to Grades array + var newGrades = new List + { + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 10 }, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 21,}, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 47 }, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 6,} + }; + var addUpdate = Builders.Update + .PushEach("Grades", newGrades); + _restaurantsCollection.UpdateMany(filter, addUpdate); + + // Remove all "Grade = F" values from Grades array + var pullUpdate = Builders.Update + .PullFilter(restaurant => restaurant.Grades, gradeEntry => gradeEntry.Grade == "F"); + + var result = _restaurantsCollection.UpdateMany(filter, pullUpdate); + + return result; + // end-update-many-pullfilter + } + + public static async Task UpdateManyPullFilterAsync() + { + // start-update-many-pullfilter-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Add GradeEntry values with "Grade = F" to Grades array + var newGrades = new List + { + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 10 }, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 21,}, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 47 }, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 6,} + }; + var addUpdate = Builders.Update + .PushEach("Grades", newGrades); + await _restaurantsCollection.UpdateManyAsync(filter, addUpdate); + + // Remove all "Grade = F" values from Grades array + var pullUpdate = Builders.Update + .PullFilter(restaurant => restaurant.Grades, gradeEntry => gradeEntry.Grade == "F"); + + var result = await _restaurantsCollection.UpdateManyAsync(filter, pullUpdate); + + return result; + // end-update-many-pullfilter-async + } + + public static UpdateResult UpdateManyPositional() + { + // start-update-many-positional + var filter = Builders.Filter + .Eq("name", "Downtown Deli") & + Builders.Filter.Eq("grades.grade", "A"); + + // Set Score = 100 in first GradeEntry where Grade = "A" + var update = Builders.Update + .Set("grades.$.score", 100); + + var result = _restaurantsCollection.UpdateMany(filter, update); + + return result; + // end-update-many-positional + } + + public static async Task UpdateManyPositionalAsync() + { + // start-update-many-positional-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli") & + Builders.Filter + .Eq("grades.grade", "A"); + + // Set Score = 100 in first GradeEntry where Grade = "A" + var update = Builders.Update + .Set("grades.$.score", 100); + + var result = await _restaurantsCollection.UpdateManyAsync(filter, update); + + return result; + // end-update-many-positional-async + } + + public static UpdateResult UpdateManyAllPositional() + { + // start-update-many-allpositional + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Set Score = 100 in all GradeEntry objects + var update = Builders.Update + .Set("grades.$[].score", 100); + + var result = _restaurantsCollection.UpdateMany(filter, update); + + return result; + // end-update-many-allpositional + } + + public static async Task UpdateManyAllPositionalAsync() + { + // start-update-many-allpositional-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Set Score = 100 in all GradeEntry objects + var update = Builders.Update + .Set("grades.$[].score", 100); + + var result = await _restaurantsCollection.UpdateManyAsync(filter, update); + + return result; + // end-update-many-allpositional-async + } + + public static UpdateResult UpdateManyFilteredPositional() + { + // start-update-many-filteredpositional + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var arrayFilters = new List + { + new BsonDocumentArrayFilterDefinition( + new BsonDocument + { + { "gradeEntry.score", new BsonDocument { { "$gte", 94} } } + }) + }; + + // Set Grade = "A" in all GradeEntry objects where Score >= 94 + var update = Builders.Update + .Set("grades.$[gradeEntry].grade", "F"); + + var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; + var result = _restaurantsCollection.UpdateMany(filter, update, updateOptions); + + return result; + // end-update-many-filteredpositional + } + + public static async Task UpdateManyFilteredPositionalAsync() + { + // start-update-many-filteredpositional-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var arrayFilters = new List + { + new BsonDocumentArrayFilterDefinition( + new BsonDocument + { + { "gradeEntry.score", new BsonDocument { { "$gte", 94} } } + }) + }; + + // Set Grade = "A" in all GradeEntry objects where Score >= 94 + var update = Builders.Update + .Set("grades.$[gradeEntry].grade", "F"); + + var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; + var result = await _restaurantsCollection.UpdateOneAsync(filter, update, updateOptions); + + return result; + // end-update-many-filteredpositional-async + } +} +} \ No newline at end of file diff --git a/source/includes/code-examples/UpdateArrays.cs b/source/includes/code-examples/UpdateOneArrays.cs similarity index 53% rename from source/includes/code-examples/UpdateArrays.cs rename to source/includes/code-examples/UpdateOneArrays.cs index 7b47d900..35ff93e8 100644 --- a/source/includes/code-examples/UpdateArrays.cs +++ b/source/includes/code-examples/UpdateOneArrays.cs @@ -1,18 +1,28 @@ using MongoDB.Bson; -using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.Conventions; using MongoDB.Driver; using WriteData.Models; -using static System.Console; namespace CSharpExamples.WriteData; -public static class UpdateArrays +public static class UpdateOneArrays { private static IMongoCollection _restaurantsCollection; //private static string _mongoConnectionString = ""; private static string _mongoConnectionString = - "mongodb+srv://mikewoofter:mikewoofter@cluster0.pw0q4.mongodb.net/?retryWrites=true&w=majority"; + "mongodb+srv://mikewoofter:mikewoofter@cluster0.pw0q4.mongodb.net/?retryWrites=true&w=majority"; + + public static void Setup() + { + // This allows automapping of the camelCase database fields to our models. + var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; + ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); + + // Establish the connection to MongoDB and get the restaurants database + var mongoClient = new MongoClient(_mongoConnectionString); + var restaurantsDatabase = mongoClient.GetDatabase("sample_restaurants"); + _restaurantsCollection = restaurantsDatabase.GetCollection("restaurants"); + } public static UpdateResult UpdateOnePush() { @@ -54,46 +64,6 @@ public static async Task UpdateOnePushAsync() // end-update-one-push-async } - public static UpdateResult UpdateManyPush() - { - // start-update-many-push - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); - - var update = Builders.Update - .Push(restaurant => restaurant.Grades, new GradeEntry() - { - Date = DateTime.Now, - Grade = "A", - Score = 96 - }); - - var result = _restaurantsCollection.UpdateMany(filter, update); - - return result; - // end-update-many-push - } - - public static async Task UpdateManyPushAsync() - { - // start-update-many-push-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); - - var update = Builders.Update - .Push(restaurant => restaurant.Grades, new GradeEntry() - { - Date = DateTime.Now, - Grade = "A", - Score = 96 - }); - - var result = await _restaurantsCollection.UpdateManyAsync(filter, update); - - return result; - // end-update-many-push-async - } - public static UpdateResult UpdateOneAddToSet() { // start-update-one-addtoset @@ -128,92 +98,6 @@ public static async Task UpdateOneAddToSetAsync() // end-update-one-addtoset-async } - public static UpdateResult UpdateManyAddToSet() - { - // start-update-many-addtoset - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); - - var firstGradeEntry = _restaurantsCollection.Find(filter).FirstOrDefault().Grades[0]; - - var update = Builders.Update - .AddToSet(restaurant => restaurant.Grades, firstGradeEntry); - - var result = _restaurantsCollection.UpdateMany(filter, update); - - return result; - // end-update-many-addtoset - } - - public static async Task UpdateManyAddToSetAsync() - { - // start-update-many-addtoset-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); - - var firstGradeEntry = _restaurantsCollection.Find(filter).FirstOrDefault().Grades[0]; - - var update = Builders.Update - .AddToSet(restaurant => restaurant.Grades, firstGradeEntry); - - var result = await _restaurantsCollection.UpdateManyAsync(filter, update); - - return result; - // end-update-many-addtoset-async - } - - public static UpdateResult UpdateManyPushEach() - { - // start-update-many-pusheach - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); - - var newGrades = new List - { - new GradeEntry { Date = DateTime.Now, Grade = "A", Score = 95 }, - new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89,} - }; - - var scoreSort = Builders.Sort.Descending(g => g.Score); - - var update = Builders.Update.PushEach( - "Grades", - newGrades, - position: 0, - sort: scoreSort); - - var result = _restaurantsCollection.UpdateMany(filter, update); - - return result; - // end-update-many-pusheach - } - - public static async Task UpdateManyPushEachAsync() - { - // start-update-many-pusheach-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); - - var newGrades = new List - { - new GradeEntry { Date = DateTime.Now, Grade = "A", Score = 95 }, - new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89,} - }; - - var scoreSort = Builders.Sort.Descending(g => g.Score); - - var update = Builders.Update.PushEach( - "Grades", - newGrades, - position: 0, - sort: scoreSort); - - var result = await _restaurantsCollection.UpdateManyAsync(filter, update); - - return result; - // end-update-many-pusheach-async - } - public static UpdateResult UpdateOnePushEach() { // start-update-one-pusheach @@ -266,38 +150,6 @@ public static async Task UpdateOnePushEachAsync() // end-update-one-pusheach-async } - - // private static void LinqTest() - // { - // var x = _restaurantsCollection.UpdateOne(l => l.Id == another.Id && l.AnArrayMember.Any(l => l.Id == anArrayId), - // Builders.Update.Set(l => l.AnArrayMember.ElementAt(-1).Deleted, true)); - // - // Builders.Update. - // } - - public static void Setup() - { - // This allows automapping of the camelCase database fields to our models. - var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; - ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); - - // Establish the connection to MongoDB and get the restaurants database - var mongoClient = new MongoClient(_mongoConnectionString); - var restaurantsDatabase = mongoClient.GetDatabase("sample_restaurants"); - _restaurantsCollection = restaurantsDatabase.GetCollection("restaurants"); - } - - public static void ResetSampleData() - { - var filter = Builders.Filter - .Eq("name", "2 Bagels 2 Buns"); - - var update = Builders.Update - .Set(restaurant => restaurant.Name, "Bagels N Buns"); - - _restaurantsCollection.UpdateOne(filter, update); - } - public static UpdateResult UpdateOneAddToSetEach() { // start-update-one-addtoseteach @@ -334,42 +186,6 @@ public static async Task UpdateOneAddToSetEachAsync() // end-update-one-addtoseteach-async } - public static UpdateResult UpdateManyAddToSetEach() - { - // start-update-many-addtoseteach - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); - - var doc = _restaurantsCollection.Find(filter).FirstOrDefault(); - var firstGradeEntries = new List { doc.Grades[0], doc.Grades[1] }; - - var update = Builders.Update - .AddToSetEach(restaurant => restaurant.Grades, firstGradeEntries); - - var result = _restaurantsCollection.UpdateMany(filter, update); - - return result; - // end-update-many-addtoseteach - } - - public static async Task UpdateManyAddToSetEachAsync() - { - // start-update-many-addtoseteach-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); - - var doc = _restaurantsCollection.Find(filter).FirstOrDefault(); - var firstGradeEntries = new List { doc.Grades[0], doc.Grades[1] }; - - var update = Builders.Update - .AddToSetEach(restaurant => restaurant.Grades, firstGradeEntries); - - var result = await _restaurantsCollection.UpdateManyAsync(filter, update); - - return result; - // end-update-many-addtoseteach-async - } - public static UpdateResult UpdateOnePopFirst() { // start-update-one-popfirst @@ -400,36 +216,6 @@ public static async Task UpdateOnePopFirstAsync() // end-update-one-popfirst-async } - public static UpdateResult UpdateManyPopFirst() - { - // start-update-many-popfirst - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); - - var update = Builders.Update - .PopFirst(restaurant => restaurant.Grades); - - var result = _restaurantsCollection.UpdateMany(filter, update); - - return result; - // end-update-many-popfirst - } - - public static async Task UpdateManyPopFirstAsync() - { - // start-update-many-popfirst-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); - - var update = Builders.Update - .PopFirst(restaurant => restaurant.Grades); - - var result = await _restaurantsCollection.UpdateManyAsync(filter, update); - - return result; - // end-update-many-popfirst-async - } - public static UpdateResult UpdateOnePopLast() { // start-update-one-poplast @@ -460,36 +246,6 @@ public static async Task UpdateOnePopLastAsync() // end-update-one-poplast-async } - public static UpdateResult UpdateManyPopLast() - { - // start-update-many-poplast - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); - - var update = Builders.Update - .PopLast(restaurant => restaurant.Grades); - - var result = _restaurantsCollection.UpdateMany(filter, update); - - return result; - // end-update-many-poplast - } - - public static async Task UpdateManyPopLastAsync() - { - // start-update-many-poplast-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); - - var update = Builders.Update - .PopLast(restaurant => restaurant.Grades); - - var result = await _restaurantsCollection.UpdateManyAsync(filter, update); - - return result; - // end-update-many-poplast-async - } - public static UpdateResult UpdateOnePull() { // start-update-one-pull @@ -542,58 +298,6 @@ public static async Task UpdateOnePullAsync() // end-update-one-pull-async } - public static UpdateResult UpdateManyPull() - { - // start-update-many-pull - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); - - // Add duplicate values to Grades array - var newGrades = new List - { - new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, - new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,} - }; - var addUpdate = Builders.Update - .PushEach("Grades", newGrades); - _restaurantsCollection.UpdateMany(filter, addUpdate); - - // Remove duplicates from Grades array - var pullUpdate = Builders.Update - .Pull(restaurant => restaurant.Grades, newGrades[0]); - - var result = _restaurantsCollection.UpdateMany(filter, pullUpdate); - - return result; - // end-update-many-pull - } - - public static async Task UpdateManyPullAsync() - { - // start-update-many-pull-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); - - // Add duplicate values to Grades array - var newGrades = new List - { - new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, - new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,} - }; - var addUpdate = Builders.Update - .PushEach("Grades", newGrades); - await _restaurantsCollection.UpdateManyAsync(filter, addUpdate); - - // Remove duplicates from Grades array - var pullUpdate = Builders.Update - .Pull(restaurant => restaurant.Grades, newGrades[0]); - - var result = await _restaurantsCollection.UpdateManyAsync(filter, pullUpdate); - - return result; - // end-update-many-pull-async - } - public static UpdateResult UpdateOnePullAll() { // start-update-one-pullall @@ -652,64 +356,6 @@ public static async Task UpdateOnePullAllAsync() // end-update-one-pullall-async } - public static UpdateResult UpdateManyPullAll() - { - // start-update-many-pullall - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); - - // Add duplicate values to Grades array - var newGrades = new List - { - new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, - new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,}, - new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85 }, - new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85,} - }; - var addUpdate = Builders.Update - .PushEach("Grades", newGrades); - _restaurantsCollection.UpdateMany(filter, addUpdate); - - // Remove duplicates from Grades array - var gradesToRemove = new List { newGrades[0], newGrades[2] }; - var pullUpdate = Builders.Update - .PullAll(restaurant => restaurant.Grades, gradesToRemove); - - var result = _restaurantsCollection.UpdateMany(filter, pullUpdate); - - return result; - // end-update-many-pullall - } - - public static async Task UpdateManyPullAllAsync() - { - // start-update-many-pullall-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); - - // Add duplicate values to Grades array - var newGrades = new List - { - new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, - new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,}, - new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85 }, - new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85,} - }; - var addUpdate = Builders.Update - .PushEach("Grades", newGrades); - await _restaurantsCollection.UpdateManyAsync(filter, addUpdate); - - // Remove duplicates from Grades array - var gradesToRemove = new List { newGrades[0], newGrades[2] }; - var pullUpdate = Builders.Update - .PullAll(restaurant => restaurant.Grades, gradesToRemove); - - var result = await _restaurantsCollection.UpdateManyAsync(filter, pullUpdate); - - return result; - // end-update-many-pullall-async - } - public static UpdateResult UpdateOnePullFilter() { // start-update-one-pullfilter @@ -766,59 +412,122 @@ public static async Task UpdateOnePullFilterAsync() // end-update-one-pullfilter-async } - public static UpdateResult UpdateManyPullFilter() + public static UpdateResult UpdateOnePositional() + { + // start-update-one-positional + var filter = Builders.Filter + .Eq("name", "Downtown Deli") & + Builders.Filter.Eq("grades.grade", "A"); + + // Set Score = 100 in first GradeEntry where Grade = "A" + var update = Builders.Update + .Set("grades.$.score", 100); + + var result = _restaurantsCollection.UpdateOne(filter, update); + + return result; + // end-update-one-positional + } + + public static async Task UpdateOnePositionalAsync() { - // start-update-many-pullfilter + // start-update-one-positional-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli") & + Builders.Filter + .Eq("grades.grade", "A"); + + // Set Score = 100 in first GradeEntry where Grade = "A" + var update = Builders.Update + .Set("grades.$.score", 100); + + var result = await _restaurantsCollection.UpdateOneAsync(filter, update); + + return result; + // end-update-one-positional-async + } + + public static UpdateResult UpdateOneAllPositional() + { + // start-update-one-allpositional var filter = Builders.Filter .Eq("name", "Downtown Deli"); - // Add GradeEntry values with "Grade = F" to Grades array - var newGrades = new List + // Set Score = 100 in all GradeEntry objects + var update = Builders.Update + .Set("grades.$[].score", 100); + + var result = _restaurantsCollection.UpdateOne(filter, update); + + return result; + // end-update-one-allpositional + } + + public static async Task UpdateOneAllPositionalAsync() + { + // start-update-one-allpositional-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Set Score = 100 in all GradeEntry objects + var update = Builders.Update + .Set("grades.$[].score", 100); + + var result = await _restaurantsCollection.UpdateOneAsync(filter, update); + + return result; + // end-update-one-allpositional-async + } + + public static UpdateResult UpdateOneFilteredPositional() + { + // start-update-one-filteredpositional + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var arrayFilters = new List { - new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 10 }, - new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 21,}, - new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 47 }, - new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 6,} + new BsonDocumentArrayFilterDefinition( + new BsonDocument + { + { "gradeEntry.score", new BsonDocument { { "$gte", 94} } } + }) }; - var addUpdate = Builders.Update - .PushEach("Grades", newGrades); - _restaurantsCollection.UpdateMany(filter, addUpdate); - // Remove all "Grade = F" values from Grades array - var pullUpdate = Builders.Update - .PullFilter(restaurant => restaurant.Grades, gradeEntry => gradeEntry.Grade == "F"); + // Set Grade = "A" in all GradeEntry objects where Score >= 94 + var update = Builders.Update + .Set("grades.$[gradeEntry].grade", "F"); - var result = _restaurantsCollection.UpdateMany(filter, pullUpdate); + var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; + var result = _restaurantsCollection.UpdateOne(filter, update, updateOptions); return result; - // end-update-many-pullfilter + // end-update-one-filteredpositional } - public static async Task UpdateManyPullFilterAsync() + public static async Task UpdateOneFilteredPositionalAsync() { - // start-update-many-pullfilter-async + // start-update-one-filteredpositional-async var filter = Builders.Filter .Eq("name", "Downtown Deli"); - // Add GradeEntry values with "Grade = F" to Grades array - var newGrades = new List + var arrayFilters = new List { - new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 10 }, - new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 21,}, - new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 47 }, - new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 6,} + new BsonDocumentArrayFilterDefinition( + new BsonDocument + { + { "gradeEntry.score", new BsonDocument { { "$gte", 94} } } + }) }; - var addUpdate = Builders.Update - .PushEach("Grades", newGrades); - await _restaurantsCollection.UpdateManyAsync(filter, addUpdate); - // Remove all "Grade = F" values from Grades array - var pullUpdate = Builders.Update - .PullFilter(restaurant => restaurant.Grades, gradeEntry => gradeEntry.Grade == "F"); + // Set Grade = "A" in all GradeEntry objects where Score >= 94 + var update = Builders.Update + .Set("grades.$[gradeEntry].grade", "F"); - var result = await _restaurantsCollection.UpdateManyAsync(filter, pullUpdate); + var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; + var result = await _restaurantsCollection.UpdateOneAsync(filter, update, updateOptions); return result; - // end-update-many-pullfilter-async + // end-update-one-filteredpositional-async } } \ No newline at end of file diff --git a/source/includes/page-templates/update.rst b/source/includes/page-templates/update.rst new file mode 100644 index 00000000..56107621 --- /dev/null +++ b/source/includes/page-templates/update.rst @@ -0,0 +1,316 @@ +Overview +-------- + +In this guide, you can learn how to use the {+driver-long+} to update +values in MongoDB documents. + +The {+driver-short+} provides the following methods to update values: + +- ``|sync-method|()``: Updates one or more fields in |single-or-multiple|. +- ``|async-method|()``: The asynchronous version of ``|sync-method|()``. + +The following sections describe these methods in more detail. + +.. note:: Method Overloads + + Many of the methods in this guide have multiple overloads. The examples + in this guide use the simplest overload for demonstration purposes. For + more information about the available overloads, see the + `API documentation. <{+new-api-root+}/index.html>`__ + +Methods and Parameters +---------------------- + +The ``|sync-method|()`` and ``|async-method|()`` methods accept the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``filter`` + - An instance of the ``FilterDefinition`` class that specifies the |document-or-documents| + to update. + To learn how to create a query filter, see :ref:`csharp-specify-query`. + + **Data Type:** `FilterDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>` + + * - ``update`` + - An instance of the ``UpdateDefinition`` class. This object specifies the kind of update + operation, the fields to update, and the new value for each field. To learn how to + create an ``UpdateDefinition`` object, + see :ref:`csharp-update-fields` and :ref:`csharp-update-arrays`. + + **Data Type:** `UpdateDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinition-1.html>`__ + + * - ``options`` + - *Optional.* An instance of the ``UpdateOptions`` class that specifies the + configuration for the update operation. The default value is ``null``. For a list + of available option, see :ref:`csharp-update-options`. + + **Data Type:** `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ + + * - ``cancellationToken`` + - *Optional.* A token that you can use to cancel the operation. + + **Data type**: ``CancellationToken`` + +Update Multiple Values +---------------------- + +The ``|sync-method|()`` and ``|async-method|()`` methods each accept only one +``UpdateDefinition`` object. The following sections describe how +to update multiple values in a single method call. + +Combined Update Definitions +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The ``Builders.Update.Combine()`` method lets you combine multiple ``UpdateDefinition`` +objects. This method accepts the following parameter: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``updates`` + - An array of update definitions to combine. + + **Data Type:** ``UpdateDefinition[]`` + +The ``Combine()`` method returns a single ``UpdateDefinition`` object that defines +multiple update operations. + +The following code example uses the ``Combine()`` method to combine a +:manual:`$set ` operation and an +:manual:`$unset ` +operation: + +.. tabs:: + + .. tab:: |sync-method| (Sync) + :tabid: |tab-id|-sync + + .. literalinclude:: /includes/code-examples/update-one/|sync-method|.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-combine-sync + :end-before: // end-combine-sync + + .. tab:: |sync-method| (Async) + :tabid: |tab-id|-async + + .. literalinclude:: /includes/code-examples/update-one/|sync-method|.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-combine-async + :end-before: // end-combine-async + +Update Pipelines +~~~~~~~~~~~~~~~~ + +If your application connects to {+mdb-server+} 4.2 or later, you can join +a sequence of update operations into a single +:manual:`aggregation pipeline. ` + +To create an update pipeline, call the ``Builders.Update.Pipeline()`` method. This method +accepts the following parameter: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``pipeline`` + - A ``PipelineDefinition`` instance that represents the update pipeline. To create + a ``PipelineDefinition`` object, create a BSON document for each update operation you + want to perform, then pass these documents to the ``PipelineDefinition.Create()`` method. + + **Data Type:** ``PipelineDefinition`` + +The ``Pipeline()`` method returns a single ``UpdateDefinition`` object that defines +multiple aggregation stages. + +The following code example uses the ``Pipeline()`` method to combine a +:manual:`$set ` operation and an +:manual:`$unset ` +operation: + +.. tabs:: + + .. tab:: |sync-method| (Sync) + :tabid: |tab-id|-sync + + .. literalinclude:: /includes/code-examples/update-one/|sync-method|.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-pipeline-sync + :end-before: // end-pipeline-sync + + .. tab:: |sync-method| (Async) + :tabid: |tab-id|-async + + .. literalinclude:: /includes/code-examples/update-one/|sync-method|.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-pipeline-async + :end-before: // end-pipeline-async + +.. note:: Unsupported Operations + + Update pipelines don't support all update operations, but they do support certain + aggregation stages not found in other update definitions. For a list of + update operations supported by pipelines, see + :manual:`Updates with Aggregation Pipeline ` + in the {+mdb-server+} manual. + +.. _csharp-update-options: + +Configuration Options +--------------------- +The ``|sync-method|()`` and ``|async-method|()`` methods optionally accept an +``UpdateOptions`` object as a parameter. You can use this argument to configure the +update operation. + +The ``UpdateOptions`` class contains the following properties: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Property + - Description + + * - ``ArrayFilters`` + - Specifies which array elements to modify for an update operation on an array field. + See :manual:`the MongoDB server manual` + for more information. + + **Data Type:** IEnumerable<`ArrayFilterDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ArrayFilterDefinition.html>`__> + + * - ``BypassDocumentValidation`` + - Specifies whether the update operation bypasses document validation. This lets you + update documents that don't meet the schema validation requirements, if any + exist. See :manual:`the MongoDB server manual` + for more information on schema validation. + + **Data Type:** ``bool?`` + + * - ``Collation`` + - Specifies the kind of language collation to use when sorting + results. See :manual:`the MongoDB server manual` + for more information on collation. + + **Data Type:** `Collation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Collation.html>`__ + + * - ``Comment`` + - Gets or sets the user-provided comment for the operation. + See :manual:`the MongoDB server manual` + for more information. + + **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ + + * - ``Hint`` + - Gets or sets the index to use to scan for documents. + See :manual:`the MongoDB server manual` + for more information. + + **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ + + * - ``IsUpsert`` + - Specifies whether the update operation performs an upsert operation if no + documents match the query filter. + See :manual:`the MongoDB server manual ` + for more information. + + **Data Type:** ``bool`` + + * - ``Let`` + - Gets or sets the let document. + See :manual:`the MongoDB server manual ` + for more information. + + **Data Type:** `BsonDocument <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonDocument.html>`__ + +Return Value +------------ + +The ``|sync-method|()`` and ``UpdateMany()`` methods return an ``UpdateResult`` +object. The ``|async-method|()`` and ``UpdateManyAsync()`` methods return an asynchronous +version of this type, a ``Task`` object. +The ``UpdateResult`` class contains the following properties: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Property + - Description + + * - ``IsAcknowledged`` + - Indicates whether the replace operation was acknowledged by MongoDB. + + **Data Type:** ``bool`` + + * - ``IsModifiedCountAvailable`` + - Indicates whether you can read the count of replaced records on the + ``ReplaceOneResult``. + + **Data Type:** ``bool`` + + * - ``MatchedCount`` + - The number of documents that matched the query filter, regardless of + whether one was replaced. + + **Data Type:** ``long`` + + * - ``ModifiedCount`` + - The number of documents replaced by the replace operation. + + **Data Type:** ``long`` + + * - ``UpsertedId`` + - The ID of the document that was upserted in the database, if the driver + performed an upsert. + + **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ + +Additional Information +---------------------- + +For runnable examples of the update operations, see the following usage +examples: + +- :ref:`csharp-update-one` +- :ref:`csharp-update-many` + +To learn more about creating query filters, see the :ref:`csharp-specify-query` guide. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +* `|sync-method|() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.|sync-method|.html>`__ +* `|async-method|() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.|async-method|.html>`__ +* `UpdateMany() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateMany.html>`__ +* `UpdateManyAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateManyAsync.html>`__ +* `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ +* `UpdateResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateResult.html>`__ + +.. _csharp-update-instruqt-lab: + +.. instruqt:: /mongodb-docs/tracks/update-a-document---c-net-driver?token=em_69t_l-j0BC_en7Uy + :title: UpdateManyAsync() Lesson + :drawer: \ No newline at end of file From 44dd731bbc867d1b98c279bc9daa7dd1efa23536 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Mon, 25 Nov 2024 16:51:17 -0600 Subject: [PATCH 18/39] templates --- .../write-operations/update-many/arrays.txt | 2 +- .../write-operations/update-many/fields.txt | 2 +- .../crud/write-operations/update-one.txt | 2 +- .../write-operations/update-one/arrays.txt | 2 +- .../write-operations/update-one/fields.txt | 2 +- source/includes/page-templates/update.rst | 28 +++++++++---------- 6 files changed, 18 insertions(+), 20 deletions(-) diff --git a/source/fundamentals/crud/write-operations/update-many/arrays.txt b/source/fundamentals/crud/write-operations/update-many/arrays.txt index 27cefdb5..1242ca98 100644 --- a/source/fundamentals/crud/write-operations/update-many/arrays.txt +++ b/source/fundamentals/crud/write-operations/update-many/arrays.txt @@ -1,4 +1,4 @@ -.. _csharp-update-arrays: +.. _csharp-update-many-arrays: ============= Update Arrays diff --git a/source/fundamentals/crud/write-operations/update-many/fields.txt b/source/fundamentals/crud/write-operations/update-many/fields.txt index 66369f17..51f55dd1 100644 --- a/source/fundamentals/crud/write-operations/update-many/fields.txt +++ b/source/fundamentals/crud/write-operations/update-many/fields.txt @@ -1,4 +1,4 @@ -.. _csharp-update-fields: +.. _csharp-update-one-fields: ============= Update Fields diff --git a/source/fundamentals/crud/write-operations/update-one.txt b/source/fundamentals/crud/write-operations/update-one.txt index d089e48e..1e96153f 100644 --- a/source/fundamentals/crud/write-operations/update-one.txt +++ b/source/fundamentals/crud/write-operations/update-one.txt @@ -1,5 +1,5 @@ .. _csharp-change-guide: -.. _csharp-update-documents: +.. _csharp-update-one: ========== Update One diff --git a/source/fundamentals/crud/write-operations/update-one/arrays.txt b/source/fundamentals/crud/write-operations/update-one/arrays.txt index 27cefdb5..8577af23 100644 --- a/source/fundamentals/crud/write-operations/update-one/arrays.txt +++ b/source/fundamentals/crud/write-operations/update-one/arrays.txt @@ -1,4 +1,4 @@ -.. _csharp-update-arrays: +.. _csharp-update-one-arrays: ============= Update Arrays diff --git a/source/fundamentals/crud/write-operations/update-one/fields.txt b/source/fundamentals/crud/write-operations/update-one/fields.txt index 66369f17..1e77d142 100644 --- a/source/fundamentals/crud/write-operations/update-one/fields.txt +++ b/source/fundamentals/crud/write-operations/update-one/fields.txt @@ -1,4 +1,4 @@ -.. _csharp-update-fields: +.. _csharp-update-many-fields: ============= Update Fields diff --git a/source/includes/page-templates/update.rst b/source/includes/page-templates/update.rst index 56107621..ae427552 100644 --- a/source/includes/page-templates/update.rst +++ b/source/includes/page-templates/update.rst @@ -41,7 +41,7 @@ The ``|sync-method|()`` and ``|async-method|()`` methods accept the following pa - An instance of the ``UpdateDefinition`` class. This object specifies the kind of update operation, the fields to update, and the new value for each field. To learn how to create an ``UpdateDefinition`` object, - see :ref:`csharp-update-fields` and :ref:`csharp-update-arrays`. + see :ref:`csharp-|tab-id|-fields` and :ref:`csharp-|tab-id|-arrays`. **Data Type:** `UpdateDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinition-1.html>`__ @@ -95,7 +95,7 @@ operation: .. tab:: |sync-method| (Sync) :tabid: |tab-id|-sync - .. literalinclude:: /includes/code-examples/update-one/|sync-method|.cs + .. literalinclude:: /includes/code-examples/|sync-method|Arrays.cs :language: csharp :copyable: true :dedent: @@ -105,7 +105,7 @@ operation: .. tab:: |sync-method| (Async) :tabid: |tab-id|-async - .. literalinclude:: /includes/code-examples/update-one/|sync-method|.cs + .. literalinclude:: /includes/code-examples/|sync-method|Arrays.cs :language: csharp :copyable: true :dedent: @@ -149,7 +149,7 @@ operation: .. tab:: |sync-method| (Sync) :tabid: |tab-id|-sync - .. literalinclude:: /includes/code-examples/update-one/|sync-method|.cs + .. literalinclude:: /includes/code-examples/|sync-method|.cs :language: csharp :copyable: true :dedent: @@ -159,7 +159,7 @@ operation: .. tab:: |sync-method| (Async) :tabid: |tab-id|-async - .. literalinclude:: /includes/code-examples/update-one/|sync-method|.cs + .. literalinclude:: /includes/code-examples/|sync-method|.cs :language: csharp :copyable: true :dedent: @@ -178,6 +178,7 @@ operation: Configuration Options --------------------- + The ``|sync-method|()`` and ``|async-method|()`` methods optionally accept an ``UpdateOptions`` object as a parameter. You can use this argument to configure the update operation. @@ -245,8 +246,8 @@ The ``UpdateOptions`` class contains the following properties: Return Value ------------ -The ``|sync-method|()`` and ``UpdateMany()`` methods return an ``UpdateResult`` -object. The ``|async-method|()`` and ``UpdateManyAsync()`` methods return an asynchronous +The ``|sync-method|()`` returns an ``UpdateResult``, and the ``|async-method|()`` +method returns an asynchronous version of this type, a ``Task`` object. The ``UpdateResult`` class contains the following properties: @@ -258,24 +259,24 @@ The ``UpdateResult`` class contains the following properties: - Description * - ``IsAcknowledged`` - - Indicates whether the replace operation was acknowledged by MongoDB. + - Indicates whether the update operation was acknowledged by MongoDB. **Data Type:** ``bool`` * - ``IsModifiedCountAvailable`` - - Indicates whether you can read the count of replaced records on the - ``ReplaceOneResult``. + - Indicates whether you can read the count of update records on the + ``UpdateResult``. **Data Type:** ``bool`` * - ``MatchedCount`` - The number of documents that matched the query filter, regardless of - whether one was replaced. + whether one was updated. **Data Type:** ``long`` * - ``ModifiedCount`` - - The number of documents replaced by the replace operation. + - The number of documents updated by the update operation. **Data Type:** ``long`` @@ -292,7 +293,6 @@ For runnable examples of the update operations, see the following usage examples: - :ref:`csharp-update-one` -- :ref:`csharp-update-many` To learn more about creating query filters, see the :ref:`csharp-specify-query` guide. @@ -304,8 +304,6 @@ guide, see the following API documentation: * `|sync-method|() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.|sync-method|.html>`__ * `|async-method|() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.|async-method|.html>`__ -* `UpdateMany() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateMany.html>`__ -* `UpdateManyAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateManyAsync.html>`__ * `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ * `UpdateResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateResult.html>`__ From 33a0c505d2d6e9fc9da0db53ac7f9f42e738bd88 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Mon, 25 Nov 2024 18:45:32 -0600 Subject: [PATCH 19/39] template edits --- .../crud/write-operations/update-one.txt | 50 ++++++++++++++++++- .../{ => update-many}/UpdateManyArrays.cs | 0 .../{ => update-one}/UpdateOneArrays.cs | 0 source/includes/page-templates/update.rst | 44 +--------------- 4 files changed, 51 insertions(+), 43 deletions(-) rename source/includes/code-examples/{ => update-many}/UpdateManyArrays.cs (100%) rename source/includes/code-examples/{ => update-one}/UpdateOneArrays.cs (100%) diff --git a/source/fundamentals/crud/write-operations/update-one.txt b/source/fundamentals/crud/write-operations/update-one.txt index 1e96153f..c70c98ff 100644 --- a/source/fundamentals/crud/write-operations/update-one.txt +++ b/source/fundamentals/crud/write-operations/update-one.txt @@ -48,4 +48,52 @@ Update One .. replacement:: one-or-many - one \ No newline at end of file + one + + .. replacement:: combine-code-example-tabs + + .. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-combine-sync + :end-before: // end-combine-sync + + .. tab:: UpdateOne (Async) + :tabid: update-one-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-combine-async + :end-before: // end-combine-async + + .. replacement:: pipeline-code-example-tabs + + .. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-pipeline-sync + :end-before: // end-pipeline-sync + + .. tab:: UpdateOne (Async) + :tabid: update-one-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-pipeline-async + :end-before: // end-pipeline-async \ No newline at end of file diff --git a/source/includes/code-examples/UpdateManyArrays.cs b/source/includes/code-examples/update-many/UpdateManyArrays.cs similarity index 100% rename from source/includes/code-examples/UpdateManyArrays.cs rename to source/includes/code-examples/update-many/UpdateManyArrays.cs diff --git a/source/includes/code-examples/UpdateOneArrays.cs b/source/includes/code-examples/update-one/UpdateOneArrays.cs similarity index 100% rename from source/includes/code-examples/UpdateOneArrays.cs rename to source/includes/code-examples/update-one/UpdateOneArrays.cs diff --git a/source/includes/page-templates/update.rst b/source/includes/page-templates/update.rst index ae427552..02e41147 100644 --- a/source/includes/page-templates/update.rst +++ b/source/includes/page-templates/update.rst @@ -90,27 +90,7 @@ The following code example uses the ``Combine()`` method to combine a :manual:`$unset ` operation: -.. tabs:: - - .. tab:: |sync-method| (Sync) - :tabid: |tab-id|-sync - - .. literalinclude:: /includes/code-examples/|sync-method|Arrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-combine-sync - :end-before: // end-combine-sync - - .. tab:: |sync-method| (Async) - :tabid: |tab-id|-async - - .. literalinclude:: /includes/code-examples/|sync-method|Arrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-combine-async - :end-before: // end-combine-async +|combine-code-example-tabs| Update Pipelines ~~~~~~~~~~~~~~~~ @@ -144,27 +124,7 @@ The following code example uses the ``Pipeline()`` method to combine a :manual:`$unset ` operation: -.. tabs:: - - .. tab:: |sync-method| (Sync) - :tabid: |tab-id|-sync - - .. literalinclude:: /includes/code-examples/|sync-method|.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-pipeline-sync - :end-before: // end-pipeline-sync - - .. tab:: |sync-method| (Async) - :tabid: |tab-id|-async - - .. literalinclude:: /includes/code-examples/|sync-method|.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-pipeline-async - :end-before: // end-pipeline-async +|pipeline-code-example-tabs .. note:: Unsupported Operations From 0a423acc64bff3260183cca32fdffb17285d080c Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Mon, 25 Nov 2024 18:56:54 -0600 Subject: [PATCH 20/39] wip --- .../crud/write-operations/update-many.txt | 433 +++--------------- .../crud/write-operations/update-one.txt | 10 +- .../code-examples/update-many/UpdateMany.cs | 47 +- .../update-many/UpdateManyArrays.cs | 4 +- .../update-one/UpdateOneArrays.cs | 4 +- 5 files changed, 76 insertions(+), 422 deletions(-) diff --git a/source/fundamentals/crud/write-operations/update-many.txt b/source/fundamentals/crud/write-operations/update-many.txt index ab3d3074..c06cbf97 100644 --- a/source/fundamentals/crud/write-operations/update-many.txt +++ b/source/fundamentals/crud/write-operations/update-many.txt @@ -1,9 +1,9 @@ .. _csharp-change-guide: -.. _csharp-update-documents: +.. _csharp-update-many: -================ -Update Documents -================ +=========== +Update Many +=========== .. contents:: On this page :local: @@ -21,374 +21,75 @@ Update Documents .. toctree:: :caption: Update Documents - Fields - Arrays + Fields + Arrays -Overview --------- +.. include:: /includes/page-templates/update.rst -In this guide, you can learn how to use the {+driver-long+} to update -values in MongoDB documents. + .. replacement:: sync-method -The {+driver-short+} provides the following methods to update values: - -- ``UpdateOne()``: Updates one or more fields in a single document. -- ``UpdateOneAsync()``: The asynchronous version of ``UpdateOne()``. -- ``UpdateMany()``: Updates one or more fields in multiple documents. -- ``UpdateManyAsync()``: The asynchronous version of ``UpdateMany()``. - -The following sections describe these methods in more detail. - -.. note:: Method Overloads - - Many of the methods in this guide have multiple overloads. The examples - in this guide use the simplest overload for demonstration purposes. For - more information about the available overloads, see the - `API documentation. <{+new-api-root+}/index.html>`__ - -.. tip:: Interactive Lab + UpdateMany - This page includes a short interactive lab that demonstrates how to - modify data by using the ``UpdateManyAsync()`` method. You can complete this - lab directly in your browser window without installing MongoDB or a code editor. - - To start the lab, click the :guilabel:`Open Interactive Tutorial` button at the - top of the page. To expand the lab to a full-screen format, click the - full-screen button (:guilabel:`â›¶`) in the top-right corner of the lab pane. - -Methods and Parameters ----------------------- - -The ``UpdateOne()``, ``UpdateOneAsync()``, ``UpdateMany()``, and ``UpdateManyAsync()`` -methods all accept the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``filter`` - - An instance of the ``FilterDefinition`` class that specifies the documents to update. - To learn how to create a query filter, see :ref:`csharp-specify-query`. - - **Data Type:** `FilterDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>` - - * - ``update`` - - An instance of the ``UpdateDefinition`` class. This object specifies the kind of update - operation, the fields to update, and the new value for each field. To learn how to - create an ``UpdateDefinition`` object, - see :ref:`csharp-update-fields` and :ref:`csharp-update-arrays`. - - **Data Type:** `UpdateDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinition-1.html>`__ - - * - ``options`` - - *Optional.* An instance of the ``UpdateOptions`` class that specifies the - configuration for the update operation. The default value is ``null``. For a list - of available option, see :ref:`csharp-update-options`. - - **Data Type:** `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ - - * - ``cancellationToken`` - - *Optional.* A token that you can use to cancel the operation. - - **Data type**: ``CancellationToken`` - -Update Multiple Values ----------------------- - -The ``UpdateOne()``, ``UpdateOneAsync()``, ``UpdateMany()``, and ``UpdateManyAsync()`` -methods each accept only one ``UpdateDefinition`` object. The following sections describe how -to update multiple values in a single method call. - -Combined Update Definitions -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The ``Builders.Update.Combine()`` method lets you combine multiple ``UpdateDefinition`` -objects. This method accepts the following parameter: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``updates`` - - An array of update definitions to combine. - - **Data Type:** ``UpdateDefinition[]`` - -The ``Combine()`` method returns a single ``UpdateDefinition`` object that defines -multiple update operations. - -The following code example uses the ``Combine()`` method to combine a -:manual:`$set ` operation and an -:manual:`$unset ` -operation: - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-sync - - .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-combine-sync - :end-before: // end-combine-sync - - .. tab:: UpdateOne (Async) - :tabid: update-one-async - - .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-combine-async - :end-before: // end-combine-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-sync - - .. literalinclude:: /includes/code-examples/update-many/UpdateMany.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-combine-sync - :end-before: // end-combine-sync - - .. tab:: UpdateMany (Async) - :tabid: update-many-async - - .. literalinclude:: /includes/code-examples/update-many/UpdateMany.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-combine-async - :end-before: // end-combine-async - -Update Pipelines -~~~~~~~~~~~~~~~~ - -If your application connects to {+mdb-server+} 4.2 or later, you can join -a sequence of update operations into a single -:manual:`aggregation pipeline. ` - -To create an update pipeline, call the ``Builders.Update.Pipeline()`` method. This method -accepts the following parameter: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``pipeline`` - - A ``PipelineDefinition`` instance that represents the update pipeline. To create - a ``PipelineDefinition`` object, create a BSON document for each update operation you - want to perform, then pass these documents to the ``PipelineDefinition.Create()`` method. - - **Data Type:** ``PipelineDefinition`` - -The ``Pipeline()`` method returns a single ``UpdateDefinition`` object that defines -multiple aggregation stages. - -The following code example uses the ``Pipeline()`` method to combine a -:manual:`$set ` operation and an -:manual:`$unset ` -operation: - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-sync - - .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-pipeline-sync - :end-before: // end-pipeline-sync + .. replacement:: async-method - .. tab:: UpdateOne (Async) - :tabid: update-one-async - - .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-pipeline-async - :end-before: // end-pipeline-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-sync - - .. literalinclude:: /includes/code-examples/update-many/UpdateMany.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-pipeline-sync - :end-before: // end-pipeline-sync - - .. tab:: UpdateMany (Async) - :tabid: update-many-async - - .. literalinclude:: /includes/code-examples/update-many/UpdateMany.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-pipeline-async - :end-before: // end-pipeline-async - -.. note:: Unsupported Operations - - Update pipelines don't support all update operations, but they do support certain - aggregation stages not found in other update definitions. For a list of - update operations supported by pipelines, see - :manual:`Updates with Aggregation Pipeline ` - in the {+mdb-server+} manual. - -.. _csharp-update-options: - -Configuration Options ---------------------- - -The update methods optionally accept an ``UpdateOptions`` object as a -parameter. You can use this argument to configure the update operation. - -The ``UpdateOptions`` class contains the following properties: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Property - - Description - - * - ``ArrayFilters`` - - Specifies which array elements to modify for an update operation on an array field. - See :manual:`the MongoDB server manual` - for more information. - - **Data Type:** IEnumerable<`ArrayFilterDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ArrayFilterDefinition.html>`__> - - * - ``BypassDocumentValidation`` - - Specifies whether the update operation bypasses document validation. This lets you - update documents that don't meet the schema validation requirements, if any - exist. See :manual:`the MongoDB server manual` - for more information on schema validation. - - **Data Type:** ``bool?`` - - * - ``Collation`` - - Specifies the kind of language collation to use when sorting - results. See :manual:`the MongoDB server manual` - for more information on collation. - - **Data Type:** `Collation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Collation.html>`__ - - * - ``Comment`` - - Gets or sets the user-provided comment for the operation. - See :manual:`the MongoDB server manual` - for more information. - - **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ - - * - ``Hint`` - - Gets or sets the index to use to scan for documents. - See :manual:`the MongoDB server manual` - for more information. - - **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ - - * - ``IsUpsert`` - - Specifies whether the update operation performs an upsert operation if no - documents match the query filter. - See :manual:`the MongoDB server manual ` - for more information. - - **Data Type:** ``bool`` - - * - ``Let`` - - Gets or sets the let document. - See :manual:`the MongoDB server manual ` - for more information. - - **Data Type:** `BsonDocument <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonDocument.html>`__ - -Return Value ------------- - -The ``UpdateOne()`` and ``UpdateMany()`` methods return an ``UpdateResult`` -object. The ``UpdateOneAsync()`` and ``UpdateManyAsync()`` methods return an asynchronous -version of this type, a ``Task`` object. -The ``UpdateResult`` class contains the following properties: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Property - - Description - - * - ``IsAcknowledged`` - - Indicates whether the replace operation was acknowledged by MongoDB. - - **Data Type:** ``bool`` + UpdateManyAsync - * - ``IsModifiedCountAvailable`` - - Indicates whether you can read the count of replaced records on the - ``ReplaceOneResult``. - - **Data Type:** ``bool`` - - * - ``MatchedCount`` - - The number of documents that matched the query filter, regardless of - whether one was replaced. - - **Data Type:** ``long`` + .. replacement:: document-or-documents - * - ``ModifiedCount`` - - The number of documents replaced by the replace operation. - - **Data Type:** ``long`` - - * - ``UpsertedId`` - - The ID of the document that was upserted in the database, if the driver - performed an upsert. - - **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ - -Additional Information ----------------------- - -For runnable examples of the update operations, see the following usage -examples: - -- :ref:`csharp-update-one` -- :ref:`csharp-update-many` - -To learn more about creating query filters, see the :ref:`csharp-specify-query` guide. - -API Documentation -~~~~~~~~~~~~~~~~~ - -To learn more about any of the methods or types discussed in this -guide, see the following API documentation: - -* `UpdateOne() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateOne.html>`__ -* `UpdateOneAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateOneAsync.html>`__ -* `UpdateMany() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateMany.html>`__ -* `UpdateManyAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateManyAsync.html>`__ -* `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ -* `UpdateResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateResult.html>`__ + documents + + .. replacement:: tab-id -.. _csharp-update-instruqt-lab: + update-many + + .. replacement:: single-or-multiple -.. instruqt:: /mongodb-docs/tracks/update-a-document---c-net-driver?token=em_69t_l-j0BC_en7Uy - :title: UpdateManyAsync() Lesson - :drawer: \ No newline at end of file + multiple documents + + .. replacement:: combine-code-example-tabs + + .. tabs:: + + .. tab:: UpdateMany (Sync) + :tabid: update-many-sync + + .. literalinclude:: /includes/code-examples/update-many/UpdateMany.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-combine-sync + :end-before: // end-combine-sync + + .. tab:: UpdateMany (Async) + :tabid: update-many-async + + .. literalinclude:: /includes/code-examples/update-many/UpdateMany.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-combine-async + :end-before: // end-combine-async + + .. replacement:: pipeline-code-example-tabs + + .. tabs:: + + .. tab:: UpdateMany (Sync) + :tabid: update-many-sync + + .. literalinclude:: /includes/code-examples/update-many/UpdateMany.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-pipeline-sync + :end-before: // end-pipeline-sync + + .. tab:: UpdateMany (Async) + :tabid: update-many-async + + .. literalinclude:: /includes/code-examples/update-many/UpdateMany.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-pipeline-async + :end-before: // end-pipeline-async \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations/update-one.txt b/source/fundamentals/crud/write-operations/update-one.txt index c70c98ff..211313b5 100644 --- a/source/fundamentals/crud/write-operations/update-one.txt +++ b/source/fundamentals/crud/write-operations/update-one.txt @@ -46,10 +46,6 @@ Update One a single document - .. replacement:: one-or-many - - one - .. replacement:: combine-code-example-tabs .. tabs:: @@ -80,17 +76,17 @@ Update One .. tab:: UpdateOne (Sync) :tabid: update-one-sync - + .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs :language: csharp :copyable: true :dedent: :start-after: // start-pipeline-sync :end-before: // end-pipeline-sync - + .. tab:: UpdateOne (Async) :tabid: update-one-async - + .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs :language: csharp :copyable: true diff --git a/source/includes/code-examples/update-many/UpdateMany.cs b/source/includes/code-examples/update-many/UpdateMany.cs index d4e0d288..56d3cdb7 100644 --- a/source/includes/code-examples/update-many/UpdateMany.cs +++ b/source/includes/code-examples/update-many/UpdateMany.cs @@ -102,7 +102,7 @@ public static void CombineUpdates() { // start-combine-sync var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + .Eq("cuisine", "Pizza"); var combinedUpdate = Builders.Update.Combine( Builders.Update.Set("cuisine", "French"), @@ -117,7 +117,7 @@ public static async Task CombineUpdatesAsync() { // start-combine-async var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + .Eq("cuisine", "Pizza"); var combinedUpdate = Builders.Update.Combine( Builders.Update.Set("cuisine", "French"), @@ -131,7 +131,7 @@ public static void PipelineUpdate() { // start-pipeline-sync var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + .Eq("cuisine", "Pizza"); var updatePipeline = Builders.Update.Pipeline( PipelineDefinition.Create( @@ -148,7 +148,7 @@ public static async Task PipelineUpdateAsync() { // start-pipeline-async var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + .Eq("cuisine", "Pizza"); var updatePipeline = Builders.Update.Pipeline( PipelineDefinition.Create( @@ -163,42 +163,3 @@ public static async Task PipelineUpdateAsync() } -public class Restaurant -{ - public ObjectId Id { get; set; } - - public string Name { get; set; } - - [BsonElement("restaurant_id")] - public string RestaurantId { get; set; } - - public string Cuisine { get; set; } - - public Address Address { get; set; } - - public string Borough { get; set; } - - public List Grades { get; set; } -} - -public class Address -{ - public string Building { get; set; } - - [BsonElement("coord")] - public double[] Coordinates { get; set; } - - public string Street { get; set; } - - [BsonElement("zipcode")] - public string ZipCode { get; set; } -} - -public class GradeEntry -{ - public DateTime Date { get; set; } - - public string Grade { get; set; } - - public float? Score { get; set; } -} diff --git a/source/includes/code-examples/update-many/UpdateManyArrays.cs b/source/includes/code-examples/update-many/UpdateManyArrays.cs index 872e56cc..720f913b 100644 --- a/source/includes/code-examples/update-many/UpdateManyArrays.cs +++ b/source/includes/code-examples/update-many/UpdateManyArrays.cs @@ -8,9 +8,7 @@ namespace CSharpExamples.WriteData; public class UpdateManyArrays { private static IMongoCollection _restaurantsCollection; - //private static string _mongoConnectionString = ""; - private static string _mongoConnectionString = - "mongodb+srv://mikewoofter:mikewoofter@cluster0.pw0q4.mongodb.net/?retryWrites=true&w=majority"; + private static string _mongoConnectionString = ""; public static void Setup() { diff --git a/source/includes/code-examples/update-one/UpdateOneArrays.cs b/source/includes/code-examples/update-one/UpdateOneArrays.cs index 35ff93e8..463c60ef 100644 --- a/source/includes/code-examples/update-one/UpdateOneArrays.cs +++ b/source/includes/code-examples/update-one/UpdateOneArrays.cs @@ -8,9 +8,7 @@ namespace CSharpExamples.WriteData; public static class UpdateOneArrays { private static IMongoCollection _restaurantsCollection; - //private static string _mongoConnectionString = ""; - private static string _mongoConnectionString = - "mongodb+srv://mikewoofter:mikewoofter@cluster0.pw0q4.mongodb.net/?retryWrites=true&w=majority"; + private static string _mongoConnectionString = ""; public static void Setup() { From 9217bc9c4a27a20de5ca2fd8016cdea4ec9142cc Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Mon, 25 Nov 2024 19:28:19 -0600 Subject: [PATCH 21/39] wip --- .../crud/write-operations/update-many.txt | 2 +- .../write-operations/update-many/arrays.txt | 937 ++---------------- .../write-operations/update-many/fields.txt | 264 +---- .../crud/write-operations/update-one.txt | 2 +- .../write-operations/update-one/fields.txt | 264 +---- .../includes/page-templates/update/arrays.rst | 798 +++++++++++++++ .../includes/page-templates/update/fields.rst | 245 +++++ .../page-templates/{ => update}/update.rst | 2 +- source/usage-examples/updateOne.txt | 2 +- 9 files changed, 1116 insertions(+), 1400 deletions(-) create mode 100644 source/includes/page-templates/update/arrays.rst create mode 100644 source/includes/page-templates/update/fields.rst rename source/includes/page-templates/{ => update}/update.rst (99%) diff --git a/source/fundamentals/crud/write-operations/update-many.txt b/source/fundamentals/crud/write-operations/update-many.txt index c06cbf97..e5756442 100644 --- a/source/fundamentals/crud/write-operations/update-many.txt +++ b/source/fundamentals/crud/write-operations/update-many.txt @@ -24,7 +24,7 @@ Update Many Fields Arrays -.. include:: /includes/page-templates/update.rst +.. include:: /includes/page-templates/update/update.rst .. replacement:: sync-method diff --git a/source/fundamentals/crud/write-operations/update-many/arrays.txt b/source/fundamentals/crud/write-operations/update-many/arrays.txt index 1242ca98..c6cf6d42 100644 --- a/source/fundamentals/crud/write-operations/update-many/arrays.txt +++ b/source/fundamentals/crud/write-operations/update-many/arrays.txt @@ -17,883 +17,60 @@ Update Arrays .. meta:: :keywords: synchronous, asynchronous -Overview --------- - -On this page, you can learn how to create ``UpdateDefinition`` objects for array fields. -An ``UpdateDefinition`` object specifies the kind of update operation to perform, the -fields to update, and the new value for each field, if applicable. - -The {+driver-short+} supports the array update operators and modifiers described in the -:manual:`{+mdb-server+} manual `. -To create an ``UpdateDefinition`` object for one of these operators, call the corresponding -method from the ``Builders.Update`` property. -The following sections describe these methods in more detail. - -After you create an ``UpdateDefinition``, pass it to one of the update methods -described on the :ref:`` page. - -.. include:: /includes/method-overloads.rst - -.. include:: /includes/atlas-sample-data.rst - -Add One Value -------------- - -To add one value to the end of an array, call the ``Builders.Update.Push()`` method. -This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to add a value to. - - **Data Type:** ``Expression>>`` - - * - ``value`` - - The value to add to the end of the array field. - - **Data Type:** ``TItem`` - -The following code example uses the ``Push()`` method to add a new ``GradeEntry`` object -to the ``Grades`` array in the matching documents: - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-push-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-push - :end-before: // end-update-one-push - - .. tab:: UpdateOne (Async) - :tabid: update-one-push-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-push-async - :end-before: // end-update-one-push-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-push-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-push - :end-before: // end-update-many-push - - .. tab:: UpdateMany (Async) - :tabid: update-many-push-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-push-async - :end-before: // end-update-many-push-async - -.. tip:: Configure the Push Operation - - To add a value at a specific position in an array, or to sort or slice the array after - updating it, call the ``PushEach()`` method instead. - TODO: link this - -To add one value to the end of an array, *but only if it doesn't already exist in the array*, -call the ``Builders.Update.AddToSet()`` method. -{+mdb-server+} determines whether the value already exists in the array by -comparing the value's BSON representation to the BSON representation of each -other element in the array. - -The ``AddToSet()`` method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to add to. - - **Data Type:** ``Expression>>`` - - * - ``value`` - - The value to add to the end of the array field. - - **Data Type:** ``TItem`` - -The following code example tries to use the ``AddToSet()`` method to re-add the first -``GradeEntry`` object to the ``Grades`` array in the matching documents. Because -the value already exists in the array, the update operation does nothing. - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-addtoset-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-addtoset - :end-before: // end-update-one-addtoset - - .. tab:: UpdateOne (Async) - :tabid: update-one-addtoset-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-addtoset-async - :end-before: // end-update-one-addtoset-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-addtoset-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-addtoset - :end-before: // end-update-many-addtoset - - .. tab:: UpdateMany (Async) - :tabid: update-many-addtoset-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-addtoset-async - :end-before: // end-update-many-addtoset-async - -Add Multiple Values -------------------- - -To add multiple values to an array, call the ``Builders.Update.PushEach()`` method. -This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to add to. - - **Data Type:** ``Expression>>`` - - * - ``values`` - - The values to add to the array field. - - **Data Type:** ``IEnumerable`` - - * - ``slice`` - - The number of elements to keep in the array, counted from the start of the array - after updates. If the value is negative, - the method keeps the specified number of elements from the end of the array. - - **Data Type:** ``int?`` - - * - ``position`` - - The position in the array at which to add the values. By default, the method - adds the values to the end of the array. - - **Data Type:** ``int?`` - - * - ``sort`` - - A ``SortDefinition`` object that specifies how the driver sorts the array elements - after adding the new values. - - **Data Type:** `SortDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.SortDefinition-1.html>`__ - -The following code example uses the ``PushEach()`` method to add two new ``GradeEntry`` -objects to the start of the ``Grades`` array. It then sorts the array elements in -descending order by the values of their ``Score`` fields. - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-pusheach-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pusheach - :end-before: // end-update-one-pusheach - - .. tab:: UpdateOne (Async) - :tabid: update-one-pusheach-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pusheach-async - :end-before: // end-update-one-pusheach-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-pusheach-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pusheach - :end-before: // end-update-many-pusheach - - .. tab:: UpdateMany (Async) - :tabid: update-many-pusheach-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pusheach-async - :end-before: // end-update-many-pusheach-async - -To add multiple values to an array, *but only if they don't already exist in the array*, -call the ``Builders.Update.AddToSetEach()`` method. -This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to add to. - - **Data Type:** ``Expression>>`` - - * - ``values`` - - The values to add to the array field. - - **Data Type:** ``IEnumerable`` - -The following code example tries to use the ``AddToSetEach()`` method to re-add the first -and second ``GradeEntry`` objects to the ``Grades`` array in the matching documents. -Because these values already exist in the array, the update operation does nothing. - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-addtoseteach-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-addtoseteach - :end-before: // end-update-one-addtoseteach - - .. tab:: UpdateOne (Async) - :tabid: update-one-addtoseteach-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-addtoseteach-async - :end-before: // end-update-one-addtoseteach-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-addtoset-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-addtoseteach - :end-before: // end-update-many-addtoseteach - - .. tab:: UpdateMany (Async) - :tabid: update-many-addtoset-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-addtoseteach-async - :end-before: // end-update-many-addtoseteach-async - -Remove Values -------------- - -To remove the first value from an array, call the ``Builders.Update.PopFirst()`` method. -This method accepts the following parameter: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to remove the first value from. - - **Data Type:** ``Expression>>`` - -The following code example uses the ``PopFirst()`` method to remove the first ``GradeEntry`` -object from the ``Grades`` array in the matching documents: - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-popfirst-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-popfirst - :end-before: // end-update-one-popfirst - - .. tab:: UpdateOne (Async) - :tabid: update-one-popfirst-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-popfirst-async - :end-before: // end-update-one-popfirst-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-popfirst-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-popfirst - :end-before: // end-update-many-popfirst - - .. tab:: UpdateMany (Async) - :tabid: update-many-popfirst-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-popfirst-async - :end-before: // end-update-many-popfirst-async - -To remove the last value from an array, call the ``Builders.Update.PopLast()`` method: -This method accepts the following parameter: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to remove the last value from. - - **Data Type:** ``Expression>>`` - -The following code example uses the ``PopLast()`` method to remove the last ``GradeEntry`` -object from the ``Grades`` array in the matching documents: - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-poplast-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-poplast - :end-before: // end-update-one-poplast - - .. tab:: UpdateOne (Async) - :tabid: update-one-poplast-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-poplast-async - :end-before: // end-update-one-poplast-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-poplast-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-poplast - :end-before: // end-update-many-poplast - - .. tab:: UpdateMany (Async) - :tabid: update-many-poplast-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-poplast-async - :end-before: // end-update-many-poplast-async - -To remove all instances of a specific value from an array, call the ``Builders.Update.Pull()`` method: -This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to add to. - - **Data Type:** ``Expression>>`` - - * - ``value`` - - The value to remove from the array field. - - **Data Type:** ``IEnumerable`` - -The following code example uses the ``Pull()`` method to remove all instances of a -a specific ``GradeEntry`` object from the ``Grades`` array in the matching documents: - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-pull-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pull - :end-before: // end-update-one-pull - - .. tab:: UpdateOne (Async) - :tabid: update-one-pull-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pull-async - :end-before: // end-update-one-pull-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-pull-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pull - :end-before: // end-update-many-pull - - .. tab:: UpdateMany (Async) - :tabid: update-many-pull-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pull-async - :end-before: // end-update-many-pull-async - -To remove all instances of more than one specific value from an array, call the -``Builders.Update.PullAll()`` method. -This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to add to. - - **Data Type:** ``Expression>>`` - - * - ``values`` - - The values to remove from the array field. - - **Data Type:** ``IEnumerable`` - -The following code example uses the ``PullAll()`` method to remove all instances of two -specific ``GradeEntry`` objects from the ``Grades`` array in the matching documents: - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-pullall-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pullall - :end-before: // end-update-one-pullall - - .. tab:: UpdateOne (Async) - :tabid: update-one-pullall-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pullall-async - :end-before: // end-update-one-pullall-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-pullall-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pullall - :end-before: // end-update-many-pullall - - .. tab:: UpdateMany (Async) - :tabid: update-many-pullall-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pullall-async - :end-before: // end-update-many-pullall-async - -To remove all values that match a specific condition from an array, call the -``Builders.Update.PullFilter()`` method. -This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to add to. - - **Data Type:** ``Expression>>`` - - * - ``filter`` - - A query filter that specifies the condition for values to remove. - - **Data Type:** `FilterDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ - -The following code example uses the ``PullFilter()`` method to remove all ``GradeEntry`` -objects where the ``Grade`` property is ``"F"`` from the ``Grades`` array in the -matching documents: - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-pullfilter-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pullfilter - :end-before: // end-update-one-pullfilter - - .. tab:: UpdateOne (Async) - :tabid: update-one-pullfilter-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pullfilter-async - :end-before: // end-update-one-pullfilter-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-pullfilter-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pullfilter - :end-before: // end-update-many-pullfilter - - .. tab:: UpdateMany (Async) - :tabid: update-many-pullfilter-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pullfilter-async - :end-before: // end-update-many-pullfilter-async - -Update Matching Values ----------------------- - -To update a value in an array field, call the ``Builders.Update.Set()`` method. -This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to update. - - **Data Type:** ``Expression>>`` - - * - ``value`` - - The new value to set in the array field. - - **Data Type:** ``TItem`` - -You can use the -:manual:`positional operator ` -in combination with the ``Set()`` method to query and update specific values in the array. -The following sections describe different ways to use the positional operator. - -First Matching Value -~~~~~~~~~~~~~~~~~~~~ - -To update only the first value in an array that matches a query filter, use the positional operator -(``$``) in combination with the ``Set()`` method. - -.. note:: - - To use the positional operator, the array field must be part of the query filter. - -The following example uses the ``Set()`` method and the positional operator to -update the ``Grades`` array in all documents that match the query filter. First, -it finds *only the first* ``GradeEntry`` object in the ``Grades`` array where the ``Grade`` property -has the value ``"A"``. Then, it updates the ``Score`` property of the first matching -``GradeEntry`` object to 100. - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-positional-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-positional - :end-before: // end-update-one-positional - - .. tab:: UpdateOne (Async) - :tabid: update-one-positional-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-positional-async - :end-before: // end-update-one-positional-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-positional-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-positional - :end-before: // end-update-many-positional - - .. tab:: UpdateMany (Async) - :tabid: update-many-positional-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-positional-async - :end-before: // end-update-many-positional-async - -All Matching Values -~~~~~~~~~~~~~~~~~~~ - -To update all values in an array that match a specified condition, use the filtered -positional operator (``$[]``) in combination with the ``Set()`` method. - -The following example uses the ``Set()`` method and the filtered positional operator -to update the ``Score`` property of all matching -``GradeEntry`` objects in the Grades`` array to 100 in all documents that match the -query filter. - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-allpositional-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-allpositional - :end-before: // end-update-one-allpositional - - .. tab:: UpdateOne (Async) - :tabid: update-one-allpositional-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-allpositional-async - :end-before: // end-update-one-allpositional-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-allpositional-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-allpositional - :end-before: // end-update-many-allpositional - - .. tab:: UpdateMany (Async) - :tabid: update-many-allpositional-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-allpositional-async - :end-before: // end-update-many-allpositional-async - -All Values -~~~~~~~~~~ - -To update all values in an array that match a query filter, use the all-positional operator -(``$[]``) in combination with the ``Set()`` method. - -The following example uses the ``Set()`` method and the all-positional operator -to update the ``Score`` property of all ``GradeEntry`` objects in the Grades`` array -to 100 in all documents that match the query filter. - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-filteredpositional-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-filteredpositional - :end-before: // end-update-one-filteredpositional - - .. tab:: UpdateOne (Async) - :tabid: update-one-filteredpositional-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-filteredpositional-async - :end-before: // end-update-one-filteredpositional-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-filteredpositional-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-filteredpositional - :end-before: // end-update-many-filteredpositional - - .. tab:: UpdateMany (Async) - :tabid: update-many-filteredpositional-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-filteredpositional-async - :end-before: // end-update-many-filteredpositional-async - - -LINQ3 Provider -~~~~~~~~~~~~~~ - -LINQ syntax contains a positional operator (``$``) that you can use to update elements in an array field. -Previous versions of the {+driver-short+} supported both the LINQ2 and LINQ3 providers. -In LINQ2, you could use ``-1`` to indicate use of the positional operator. - -For example, the ``Restaurant`` class contains an array field named ``Grades`` that -contains multiple ``GradeEntry`` elements. If your application were using the LINQ2 -provider, you could use the following code sample to update the -``Grade`` field of the first element in this array: - -.. code-block:: csharp - :linenos: - - var anArrayId = ObjectId.GenerateNewId(); - var another = new Restaurant - { - Id = ObjectId.GenerateNewId(), - AnArrayMember = new List - { - new AnArrayClass { Id = anArrayId, Deleted = false } - } - }; - - await collection.UpdateOneAsync( - r => r.Id == "targetId" && r.AnArrayMember.Any(l => l.Id == anArrayId), - Builders.Update.Set(l => l.AnArrayMember.ElementAt(-1).Deleted, true)); - -.. code-block:: csharp - :linenos: - - var anArrayId = ObjectId.GenerateNewId(); - var another = new Restaurant - { - Id = ObjectId.GenerateNewId(), - AnArrayMember = new List - { - new AnArrayClass { Id = anArrayId, Deleted = false } - } - }; - - await collection.UpdateOneAsync( - r => r.Id == "targetId" && r.AnArrayMember.Any(l => l.Id == anArrayId), - Builders.Update.Set(l => l.AnArrayMember.ElementAt(-1).Deleted, true)); - -This no longer works in LINQ3. Instead, you must use the following syntax: +.. include:: /includes/page-templates/update/arrays.rst + + .. replacement:: sync-method + + UpdateMany + + .. replacement:: file-folder + + update-many + + .. replacement:: matching-document-or-documents + + all matching documents + + .. replacement:: push-code-example-tabs + + .. tab:: UpdateMany (Sync) + :tabid: update-many-push-sync + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-push + :end-before: // end-update-many-push + + .. tab:: UpdateMany (Async) + :tabid: update-many-push-async + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-push-async + :end-before: // end-update-many-push-async + + .. replacement:: addtoset-code-example-tabs + + .. tab:: UpdateMany (Sync) + :tabid: update-many-addtoset-sync + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-addtoset + :end-before: // end-update-many-addtoset + + .. tab:: UpdateMany (Async) + :tabid: update-many-addtoset-async + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-addtoset-async + :end-before: // end-update-many-addtoset-async \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations/update-many/fields.txt b/source/fundamentals/crud/write-operations/update-many/fields.txt index 51f55dd1..f03c67be 100644 --- a/source/fundamentals/crud/write-operations/update-many/fields.txt +++ b/source/fundamentals/crud/write-operations/update-many/fields.txt @@ -1,4 +1,4 @@ -.. _csharp-update-one-fields: +.. _csharp-update-many-fields: ============= Update Fields @@ -17,264 +17,12 @@ Update Fields .. meta:: :keywords: synchronous, asynchronous -Overview --------- +.. include:: /includes/page-templates/update/fields.rst -On this page, you can learn how to use the {+driver-long+} to update -fields in MongoDB documents. This page describes how to create ``UpdateDefinition`` -objects that specify the update operations you want to perform on fields. -You can pass these objects to the update methods described on the -:ref:`` page. + .. replacement:: one-or-multiple -The {+driver-short+} supports the field update operators described in the -:manual:`{+mdb-server+} manual `. To specify an -update operation, call the corresponding method from the ``Builders.Update`` property. -The following sections describe these methods in more detail. + multiple MongoDB documents -.. tip:: Interactive Lab - - This page includes a short interactive lab that demonstrates how to - modify data by using the ``UpdateManyAsync()`` method. You can complete this - lab directly in your browser window without installing MongoDB or a code editor. + .. replacement:: file-folder - To start the lab, click the :guilabel:`Open Interactive Tutorial` button at the - top of the page. To expand the lab to a full-screen format, click the - full-screen button (:guilabel:`â›¶`) in the top-right corner of the lab pane. - -.. note:: Method Overloads - - Many of the methods in this guide have multiple overloads. The examples - in this guide use the simplest overload for demonstration purposes. For - more information about the available overloads, see the - :manual:`{+new-api-root+} API documentation `. - -Sample Data -~~~~~~~~~~~ - -The examples in this guide use the ``restaurants`` collection -from the ``sample_restaurants`` database. The documents in this -collection use the following ``Restaurant``, ``Address``, and ``GradeEntry`` -classes as models: - -.. literalinclude:: /includes/code-examples/Restaurant.cs - :language: csharp - :copyable: - :dedent: - -.. literalinclude:: /includes/code-examples/Address.cs - :language: csharp - :copyable: - :dedent: - -.. literalinclude:: /includes/code-examples/GradeEntry.cs - :language: csharp - :copyable: - :dedent: - -.. include:: /includes/convention-pack-note.rst - -This collection is from the :atlas:`sample datasets ` provided -by Atlas. See the :ref:`` to learn how to create a free MongoDB cluster -and load this sample data. - -.. _csharp-update-operation: - -Increment a Value ------------------ - -To increment the value of a field by a specific amount, call the ``Builders.Update.Inc()`` -method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to increment. - - **Data Type:** ``Expression>`` - - * - ``value`` - - The amount to increment the field by. - - **Data Type:** ``TField`` - -Set If Lower or Greater ------------------------ - -To update the value of the field to a specified value, *but only if the specified value -is greater than the current value of the field,* call the ``Builders.Update.Max()`` -method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to update. - - **Data Type:** ``Expression>`` - - * - ``value`` - - The value to set the field to. - - **Data Type:** ``TField`` - -To update the value of the field to a specified value, *but only if the specified value -is lesser than the current value of the field,* call the ``Builders.Update.Min()`` -method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to update. - - **Data Type:** ``Expression>`` - - * - ``value`` - - The value to set the field to. - - **Data Type:** ``TField`` - -Multiply a Value ---------------- - -To multiply the value of a field by a specific amount, call the ``Builders.Update.Mul()`` -method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to update. - - **Data Type:** ``Expression>`` - - * - ``value`` - - The amount to multiply the field by. - - **Data Type:** ``TField`` - -Rename a Field --------------- - -To rename a field, call the ``Builders.Update.Rename()`` method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to rename. - - **Data Type:** ``Expression>`` - - * - ``newName`` - - The new name for the field. - - **Data Type:** ``string`` - -Set a Value ------------ - -To set the value of a field to a specific value, call the ``Builders.Update.Set()`` -method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to update. - - **Data Type:** ``Expression>`` - - * - ``value`` - - The value to set the field to. - - **Data Type:** ``TField`` - -Unset a Field -------------- - -To remove a field from a document, call the ``Builders.Update.Unset()`` method. This method accepts the following parameter: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to remove. - - **Data Type:** ``Expression>`` - -Set on Insert -------------- - -To set the value of a field only if the document is an upsert, call the ``Builders.Update.SetOnInsert()`` -method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to update. - - **Data Type:** ``Expression>`` - - * - ``value`` - - The value to set the field to. - - **Data Type:** ``TField`` - -Set the Current Date --------------------- - -To set the value of a field to the current date and time, call the ``Builders.Update.CurrentDate()`` -method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to update. - - **Data Type:** ``Expression>`` - - * - ``type`` - - The format of the date and time, defined in the ``UpdateDefinitionCurrentDateType`` - enum. The default value is ``null``. - - **Data Type:** `UpdateDefinitionCurrentDateType? <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionCurrentDateType.html>`__ \ No newline at end of file + update-many \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations/update-one.txt b/source/fundamentals/crud/write-operations/update-one.txt index 211313b5..27e96422 100644 --- a/source/fundamentals/crud/write-operations/update-one.txt +++ b/source/fundamentals/crud/write-operations/update-one.txt @@ -24,7 +24,7 @@ Update One Fields Arrays -.. include:: /includes/page-templates/update.rst +.. include:: /includes/page-templates/update/update.rst .. replacement:: sync-method diff --git a/source/fundamentals/crud/write-operations/update-one/fields.txt b/source/fundamentals/crud/write-operations/update-one/fields.txt index 1e77d142..575f795c 100644 --- a/source/fundamentals/crud/write-operations/update-one/fields.txt +++ b/source/fundamentals/crud/write-operations/update-one/fields.txt @@ -1,4 +1,4 @@ -.. _csharp-update-many-fields: +.. _csharp-update-one-fields: ============= Update Fields @@ -17,264 +17,12 @@ Update Fields .. meta:: :keywords: synchronous, asynchronous -Overview --------- +.. include:: /includes/page-templates/update/fields.rst -On this page, you can learn how to use the {+driver-long+} to update -fields in MongoDB documents. This page describes how to create ``UpdateDefinition`` -objects that specify the update operations you want to perform on fields. -You can pass these objects to the update methods described on the -:ref:`` page. + .. replacement:: one-or-multiple -The {+driver-short+} supports the field update operators described in the -:manual:`{+mdb-server+} manual `. To specify an -update operation, call the corresponding method from the ``Builders.Update`` property. -The following sections describe these methods in more detail. + one MongoDB document -.. tip:: Interactive Lab - - This page includes a short interactive lab that demonstrates how to - modify data by using the ``UpdateManyAsync()`` method. You can complete this - lab directly in your browser window without installing MongoDB or a code editor. + .. replacement:: file-folder - To start the lab, click the :guilabel:`Open Interactive Tutorial` button at the - top of the page. To expand the lab to a full-screen format, click the - full-screen button (:guilabel:`â›¶`) in the top-right corner of the lab pane. - -.. note:: Method Overloads - - Many of the methods in this guide have multiple overloads. The examples - in this guide use the simplest overload for demonstration purposes. For - more information about the available overloads, see the - :manual:`{+new-api-root+} API documentation `. - -Sample Data -~~~~~~~~~~~ - -The examples in this guide use the ``restaurants`` collection -from the ``sample_restaurants`` database. The documents in this -collection use the following ``Restaurant``, ``Address``, and ``GradeEntry`` -classes as models: - -.. literalinclude:: /includes/code-examples/Restaurant.cs - :language: csharp - :copyable: - :dedent: - -.. literalinclude:: /includes/code-examples/Address.cs - :language: csharp - :copyable: - :dedent: - -.. literalinclude:: /includes/code-examples/GradeEntry.cs - :language: csharp - :copyable: - :dedent: - -.. include:: /includes/convention-pack-note.rst - -This collection is from the :atlas:`sample datasets ` provided -by Atlas. See the :ref:`` to learn how to create a free MongoDB cluster -and load this sample data. - -.. _csharp-update-operation: - -Increment a Value ------------------ - -To increment the value of a field by a specific amount, call the ``Builders.Update.Inc()`` -method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to increment. - - **Data Type:** ``Expression>`` - - * - ``value`` - - The amount to increment the field by. - - **Data Type:** ``TField`` - -Set If Lower or Greater ------------------------ - -To update the value of the field to a specified value, *but only if the specified value -is greater than the current value of the field,* call the ``Builders.Update.Max()`` -method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to update. - - **Data Type:** ``Expression>`` - - * - ``value`` - - The value to set the field to. - - **Data Type:** ``TField`` - -To update the value of the field to a specified value, *but only if the specified value -is lesser than the current value of the field,* call the ``Builders.Update.Min()`` -method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to update. - - **Data Type:** ``Expression>`` - - * - ``value`` - - The value to set the field to. - - **Data Type:** ``TField`` - -Multiply a Value ---------------- - -To multiply the value of a field by a specific amount, call the ``Builders.Update.Mul()`` -method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to update. - - **Data Type:** ``Expression>`` - - * - ``value`` - - The amount to multiply the field by. - - **Data Type:** ``TField`` - -Rename a Field --------------- - -To rename a field, call the ``Builders.Update.Rename()`` method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to rename. - - **Data Type:** ``Expression>`` - - * - ``newName`` - - The new name for the field. - - **Data Type:** ``string`` - -Set a Value ------------ - -To set the value of a field to a specific value, call the ``Builders.Update.Set()`` -method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to update. - - **Data Type:** ``Expression>`` - - * - ``value`` - - The value to set the field to. - - **Data Type:** ``TField`` - -Unset a Field -------------- - -To remove a field from a document, call the ``Builders.Update.Unset()`` method. This method accepts the following parameter: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to remove. - - **Data Type:** ``Expression>`` - -Set on Insert -------------- - -To set the value of a field only if the document is an upsert, call the ``Builders.Update.SetOnInsert()`` -method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to update. - - **Data Type:** ``Expression>`` - - * - ``value`` - - The value to set the field to. - - **Data Type:** ``TField`` - -Set the Current Date --------------------- - -To set the value of a field to the current date and time, call the ``Builders.Update.CurrentDate()`` -method. This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the field to update. - - **Data Type:** ``Expression>`` - - * - ``type`` - - The format of the date and time, defined in the ``UpdateDefinitionCurrentDateType`` - enum. The default value is ``null``. - - **Data Type:** `UpdateDefinitionCurrentDateType? <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionCurrentDateType.html>`__ \ No newline at end of file + update-one \ No newline at end of file diff --git a/source/includes/page-templates/update/arrays.rst b/source/includes/page-templates/update/arrays.rst new file mode 100644 index 00000000..ad32b913 --- /dev/null +++ b/source/includes/page-templates/update/arrays.rst @@ -0,0 +1,798 @@ +Overview +-------- + +On this page, you can learn how to create ``UpdateDefinition`` objects for array fields. +An ``UpdateDefinition`` object specifies the kind of update operation to perform, the +fields to update, and the new value for each field, if applicable. + +The {+driver-short+} supports the array update operators and modifiers described in the +:manual:`{+mdb-server+} manual `. +To create an ``UpdateDefinition`` object for one of these operators, call the corresponding +method from the ``Builders.Update`` property. +The following sections describe these methods in more detail. + +After you create an ``UpdateDefinition`` object, pass it to the ``|sync-method|()`` +or ``|sync-method|Async()`` method. For more information about these methods, see +the :ref:`` page. + +.. include:: /includes/method-overloads.rst + +.. include:: /includes/atlas-sample-data.rst + +Add One Value +------------- + +To add one value to the end of an array, call the ``Builders.Update.Push()`` method. +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add a value to. + + **Data Type:** ``Expression>>`` + + * - ``value`` + - The value to add to the end of the array field. + + **Data Type:** ``TItem`` + +The following code example uses the ``Push()`` method to add a new ``GradeEntry`` object +to the ``Grades`` array in |matching-document-or-documents|: + +|push-code-example-tabs| + +.. tip:: Configure the Push Operation + + To add a value at a specific position in an array, or to sort or slice the array after + updating it, call the ``PushEach()`` method instead. + +To add one value to the end of an array, *but only if it doesn't already exist in the array*, +call the ``Builders.Update.AddToSet()`` method. +{+mdb-server+} determines whether the value already exists in the array by +comparing the value's BSON representation to the BSON representation of each +other element in the array. + +The ``AddToSet()`` method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``value`` + - The value to add to the end of the array field. + + **Data Type:** ``TItem`` + +The following code example calls the ``AddToSet()`` method to re-add the first +``GradeEntry`` object to the ``Grades`` array in |matching-document-or-documents|. Because +the value already exists in the array, the update operation does nothing. + +Add Multiple Values +------------------- + +To add multiple values to an array, call the ``Builders.Update.PushEach()`` method. +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``values`` + - The values to add to the array field. + + **Data Type:** ``IEnumerable`` + + * - ``slice`` + - The number of elements to keep in the array, counted from the start of the array + after updates. If the value is negative, + the method keeps the specified number of elements from the end of the array. + + **Data Type:** ``int?`` + + * - ``position`` + - The position in the array at which to add the values. By default, the method + adds the values to the end of the array. + + **Data Type:** ``int?`` + + * - ``sort`` + - A ``SortDefinition`` object that specifies how the driver sorts the array elements + after adding the new values. + + **Data Type:** `SortDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.SortDefinition-1.html>`__ + +The following code example uses the ``PushEach()`` method to add two new ``GradeEntry`` +objects to the start of the ``Grades`` array. It then sorts the array elements in +descending order by the values of their ``Score`` fields. + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-pusheach-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pusheach + :end-before: // end-update-one-pusheach + + .. tab:: UpdateOne (Async) + :tabid: update-one-pusheach-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pusheach-async + :end-before: // end-update-one-pusheach-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-pusheach-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pusheach + :end-before: // end-update-many-pusheach + + .. tab:: UpdateMany (Async) + :tabid: update-many-pusheach-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pusheach-async + :end-before: // end-update-many-pusheach-async + +To add multiple values to an array, *but only if they don't already exist in the array*, +call the ``Builders.Update.AddToSetEach()`` method. +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``values`` + - The values to add to the array field. + + **Data Type:** ``IEnumerable`` + +The following code example tries to use the ``AddToSetEach()`` method to re-add the first +and second ``GradeEntry`` objects to the ``Grades`` array in |matching-document-or-documents|. +Because these values already exist in the array, the update operation does nothing. + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-addtoseteach-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-addtoseteach + :end-before: // end-update-one-addtoseteach + + .. tab:: UpdateOne (Async) + :tabid: update-one-addtoseteach-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-addtoseteach-async + :end-before: // end-update-one-addtoseteach-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-addtoset-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-addtoseteach + :end-before: // end-update-many-addtoseteach + + .. tab:: UpdateMany (Async) + :tabid: update-many-addtoset-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-addtoseteach-async + :end-before: // end-update-many-addtoseteach-async + +Remove Values +------------- + +To remove the first value from an array, call the ``Builders.Update.PopFirst()`` method. +This method accepts the following parameter: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to remove the first value from. + + **Data Type:** ``Expression>>`` + +The following code example uses the ``PopFirst()`` method to remove the first ``GradeEntry`` +object from the ``Grades`` array in |matching-document-or-documents|: + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-popfirst-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-popfirst + :end-before: // end-update-one-popfirst + + .. tab:: UpdateOne (Async) + :tabid: update-one-popfirst-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-popfirst-async + :end-before: // end-update-one-popfirst-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-popfirst-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-popfirst + :end-before: // end-update-many-popfirst + + .. tab:: UpdateMany (Async) + :tabid: update-many-popfirst-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-popfirst-async + :end-before: // end-update-many-popfirst-async + +To remove the last value from an array, call the ``Builders.Update.PopLast()`` method: +This method accepts the following parameter: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to remove the last value from. + + **Data Type:** ``Expression>>`` + +The following code example uses the ``PopLast()`` method to remove the last ``GradeEntry`` +object from the ``Grades`` array in |matching-document-or-documents|: + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-poplast-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-poplast + :end-before: // end-update-one-poplast + + .. tab:: UpdateOne (Async) + :tabid: update-one-poplast-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-poplast-async + :end-before: // end-update-one-poplast-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-poplast-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-poplast + :end-before: // end-update-many-poplast + + .. tab:: UpdateMany (Async) + :tabid: update-many-poplast-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-poplast-async + :end-before: // end-update-many-poplast-async + +To remove all instances of a specific value from an array, call the ``Builders.Update.Pull()`` method: +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``value`` + - The value to remove from the array field. + + **Data Type:** ``IEnumerable`` + +The following code example uses the ``Pull()`` method to remove all instances of a +a specific ``GradeEntry`` object from the ``Grades`` array in |matching-document-or-documents|: + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-pull-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pull + :end-before: // end-update-one-pull + + .. tab:: UpdateOne (Async) + :tabid: update-one-pull-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pull-async + :end-before: // end-update-one-pull-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-pull-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pull + :end-before: // end-update-many-pull + + .. tab:: UpdateMany (Async) + :tabid: update-many-pull-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pull-async + :end-before: // end-update-many-pull-async + +To remove all instances of more than one specific value from an array, call the +``Builders.Update.PullAll()`` method. +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``values`` + - The values to remove from the array field. + + **Data Type:** ``IEnumerable`` + +The following code example uses the ``PullAll()`` method to remove all instances of two +specific ``GradeEntry`` objects from the ``Grades`` array in |matching-document-or-documents|: + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-pullall-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pullall + :end-before: // end-update-one-pullall + + .. tab:: UpdateOne (Async) + :tabid: update-one-pullall-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pullall-async + :end-before: // end-update-one-pullall-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-pullall-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pullall + :end-before: // end-update-many-pullall + + .. tab:: UpdateMany (Async) + :tabid: update-many-pullall-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pullall-async + :end-before: // end-update-many-pullall-async + +To remove all values that match a specific condition from an array, call the +``Builders.Update.PullFilter()`` method. +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to add to. + + **Data Type:** ``Expression>>`` + + * - ``filter`` + - A query filter that specifies the condition for values to remove. + + **Data Type:** `FilterDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ + +The following code example uses the ``PullFilter()`` method to remove all ``GradeEntry`` +objects where the ``Grade`` property is ``"F"`` from the ``Grades`` array in the +matching documents: + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-pullfilter-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pullfilter + :end-before: // end-update-one-pullfilter + + .. tab:: UpdateOne (Async) + :tabid: update-one-pullfilter-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pullfilter-async + :end-before: // end-update-one-pullfilter-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-pullfilter-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pullfilter + :end-before: // end-update-many-pullfilter + + .. tab:: UpdateMany (Async) + :tabid: update-many-pullfilter-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pullfilter-async + :end-before: // end-update-many-pullfilter-async + +Update Matching Values +---------------------- + +To update a value in an array field, call the ``Builders.Update.Set()`` method. +This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the array field to update. + + **Data Type:** ``Expression>>`` + + * - ``value`` + - The new value to set in the array field. + + **Data Type:** ``TItem`` + +You can use the +:manual:`positional operator ` +in combination with the ``Set()`` method to query and update specific values in the array. +The following sections describe different ways to use the positional operator. + +First Matching Value +~~~~~~~~~~~~~~~~~~~~ + +To update only the first value in an array that matches a query filter, use the positional operator +(``$``) in combination with the ``Set()`` method. + +.. note:: + + To use the positional operator, the array field must be part of the query filter. + +The following example uses the ``Set()`` method and the positional operator to +update the ``Grades`` array in all documents that match the query filter. First, +it finds *only the first* ``GradeEntry`` object in the ``Grades`` array where the ``Grade`` property +has the value ``"A"``. Then, it updates the ``Score`` property of the first matching +``GradeEntry`` object to 100. + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-positional-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-positional + :end-before: // end-update-one-positional + + .. tab:: UpdateOne (Async) + :tabid: update-one-positional-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-positional-async + :end-before: // end-update-one-positional-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-positional-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-positional + :end-before: // end-update-many-positional + + .. tab:: UpdateMany (Async) + :tabid: update-many-positional-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-positional-async + :end-before: // end-update-many-positional-async + +All Matching Values +~~~~~~~~~~~~~~~~~~~ + +To update all values in an array that match a specified condition, use the filtered +positional operator (``$[]``) in combination with the ``Set()`` method. + +The following example uses the ``Set()`` method and the filtered positional operator +to update the ``Score`` property of all matching +``GradeEntry`` objects in the Grades`` array to 100 in all documents that match the +query filter. + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-allpositional-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-allpositional + :end-before: // end-update-one-allpositional + + .. tab:: UpdateOne (Async) + :tabid: update-one-allpositional-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-allpositional-async + :end-before: // end-update-one-allpositional-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-allpositional-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-allpositional + :end-before: // end-update-many-allpositional + + .. tab:: UpdateMany (Async) + :tabid: update-many-allpositional-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-allpositional-async + :end-before: // end-update-many-allpositional-async + +All Values +~~~~~~~~~~ + +To update all values in an array that match a query filter, use the all-positional operator +(``$[]``) in combination with the ``Set()`` method. + +The following example uses the ``Set()`` method and the all-positional operator +to update the ``Score`` property of all ``GradeEntry`` objects in the Grades`` array +to 100 in all documents that match the query filter. + +.. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-filteredpositional-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-filteredpositional + :end-before: // end-update-one-filteredpositional + + .. tab:: UpdateOne (Async) + :tabid: update-one-filteredpositional-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-filteredpositional-async + :end-before: // end-update-one-filteredpositional-async + + .. tab:: UpdateMany (Sync) + :tabid: update-many-filteredpositional-sync + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-filteredpositional + :end-before: // end-update-many-filteredpositional + + .. tab:: UpdateMany (Async) + :tabid: update-many-filteredpositional-async + + .. literalinclude:: /includes/code-examples/UpdateArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-filteredpositional-async + :end-before: // end-update-many-filteredpositional-async + + +LINQ3 Provider +~~~~~~~~~~~~~~ + +LINQ syntax contains a positional operator (``$``) that you can use to update elements in an array field. +Previous versions of the {+driver-short+} supported both the LINQ2 and LINQ3 providers. +In LINQ2, you could use ``-1`` to indicate use of the positional operator. + +For example, the ``Restaurant`` class contains an array field named ``Grades`` that +contains multiple ``GradeEntry`` elements. If your application were using the LINQ2 +provider, you could use the following code sample to update the +``Grade`` field of the first element in this array: + +.. code-block:: csharp + :linenos: + + var anArrayId = ObjectId.GenerateNewId(); + var another = new Restaurant + { + Id = ObjectId.GenerateNewId(), + AnArrayMember = new List + { + new AnArrayClass { Id = anArrayId, Deleted = false } + } + }; + + await collection.UpdateOneAsync( + r => r.Id == "targetId" && r.AnArrayMember.Any(l => l.Id == anArrayId), + Builders.Update.Set(l => l.AnArrayMember.ElementAt(-1).Deleted, true)); + +.. code-block:: csharp + :linenos: + + var anArrayId = ObjectId.GenerateNewId(); + var another = new Restaurant + { + Id = ObjectId.GenerateNewId(), + AnArrayMember = new List + { + new AnArrayClass { Id = anArrayId, Deleted = false } + } + }; + + await collection.UpdateOneAsync( + r => r.Id == "targetId" && r.AnArrayMember.Any(l => l.Id == anArrayId), + Builders.Update.Set(l => l.AnArrayMember.ElementAt(-1).Deleted, true)); + +This no longer works in LINQ3. Instead, you must use the following syntax: \ No newline at end of file diff --git a/source/includes/page-templates/update/fields.rst b/source/includes/page-templates/update/fields.rst new file mode 100644 index 00000000..9126256c --- /dev/null +++ b/source/includes/page-templates/update/fields.rst @@ -0,0 +1,245 @@ +Overview +-------- + +On this page, you can learn how to use the {+driver-long+} to update +fields in |one-or-multiple|. This page describes how to create ``UpdateDefinition`` +objects that specify the update operations you want to perform on fields. +You can pass these objects to the update methods described on the +:ref:`` page. + +The {+driver-short+} supports the field update operators described in the +:manual:`{+mdb-server+} manual `. To specify an +update operation, call the corresponding method from the ``Builders.Update`` property. +The following sections describe these methods in more detail. + +.. tip:: Interactive Lab + + This page includes a short interactive lab that demonstrates how to + modify data by using the ``UpdateManyAsync()`` method. You can complete this + lab directly in your browser window without installing MongoDB or a code editor. + + To start the lab, click the :guilabel:`Open Interactive Tutorial` button at the + top of the page. To expand the lab to a full-screen format, click the + full-screen button (:guilabel:`â›¶`) in the top-right corner of the lab pane. + +.. include:: /includes/method-overloads.rst + +.. include:: /includes/atlas-sample-data.rst + +Increment a Value +----------------- + +To increment the value of a field by a specific amount, call the ``Builders.Update.Inc()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to increment. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The amount to increment the field by. + + **Data Type:** ``TField`` + +Multiply a Value +---------------- + +To multiply the value of a field by a specific amount, call the ``Builders.Update.Mul()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The amount to multiply the field by. + + **Data Type:** ``TField`` + +Rename a Field +-------------- + +To rename a field, call the ``Builders.Update.Rename()`` method. This method accepts +the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to rename. + + **Data Type:** ``Expression>`` + + * - ``newName`` + - The new name for the field. + + **Data Type:** ``string`` + +Set a Value +----------- + +To set the value of a field to a specific value, call the ``Builders.Update.Set()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The value to set the field to. + + **Data Type:** ``TField`` + +Set If Lower or Greater +----------------------- + +To update the value of the field to a specified value, but only if the specified value +is *greater than* the current value of the field, call the ``Builders.Update.Max()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The value to set the field to. + + **Data Type:** ``TField`` + +To update the value of the field to a specified value, but only if the specified value +is *less than* the current value of the field, call the ``Builders.Update.Min()`` +method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The value to set the field to. + + **Data Type:** ``TField`` + +Set on Insert +------------- + +To set the value of a field only if the document was upserted by the same operation, call the +``Builders.Update.SetOnInsert()`` method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``value`` + - The value to set the field to. + + **Data Type:** ``TField`` + +Set the Current Date +-------------------- + +To set the value of a field to the current date and time, call the +``Builders.Update.CurrentDate()`` method. This method accepts the following parameters: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to update. + + **Data Type:** ``Expression>`` + + * - ``type`` + - The format of the date and time, defined in the ``UpdateDefinitionCurrentDateType`` + enum. The default value is ``null``. + + **Data Type:** `UpdateDefinitionCurrentDateType? <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionCurrentDateType.html>`__ + +Unset a Field +------------- + +To remove a field from a document, call the ``Builders.Update.Unset()`` method. This +method accepts the following parameter: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Parameter + - Description + + * - ``field`` + - An expression that specifies the field to remove. + + **Data Type:** ``Expression>`` + +API Documentation +----------------- + +For more information about any of the methods or types discussed in this +guide, see the following API documentation: + +- `Builders.Update.Inc() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders.Update.Inc-2.html>`__ +- `Builders.Update.Mul() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders.Update.Mul-2.html>`__ +- `Builders.Update.Rename() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders.Update.Rename-2.html>`__ +- `Builders.Update.Set() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders.Update.Set-2.html>`__ +- `Builders.Update.Max() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders.Update.Max-2.html>`__ +- `Builders.Update.Min() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders.Update.Min-2.html>`__ +- `Builders.Update.SetOnInsert() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders.Update.SetOnInsert-2.html>`__ +- `Builders.Update.CurrentDate() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders.Update.CurrentDate-2.html>`__ +- `Builders.Update.Unset() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders.Update.Unset-2.html>`__ \ No newline at end of file diff --git a/source/includes/page-templates/update.rst b/source/includes/page-templates/update/update.rst similarity index 99% rename from source/includes/page-templates/update.rst rename to source/includes/page-templates/update/update.rst index 02e41147..f65b18f2 100644 --- a/source/includes/page-templates/update.rst +++ b/source/includes/page-templates/update/update.rst @@ -259,7 +259,7 @@ To learn more about creating query filters, see the :ref:`csharp-specify-query` API Documentation ~~~~~~~~~~~~~~~~~ -To learn more about any of the methods or types discussed in this +For more information about any of the methods or types discussed in this guide, see the following API documentation: * `|sync-method|() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.|sync-method|.html>`__ diff --git a/source/usage-examples/updateOne.txt b/source/usage-examples/updateOne.txt index eecfb94b..9dc8207c 100644 --- a/source/usage-examples/updateOne.txt +++ b/source/usage-examples/updateOne.txt @@ -1,4 +1,4 @@ -.. _csharp-update-one: +.. _csharp-examples-update-one: ================= Update a Document From 34e6c4a4d28a0f84b40218aa0cb9b29fcfdd15be Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Tue, 26 Nov 2024 09:01:04 -0600 Subject: [PATCH 22/39] wip --- source/fundamentals/crud/write-operations.txt | 6 +- .../write-operations/update-many/arrays.txt | 322 ++++- .../write-operations/update-many/fields.txt | 4 +- .../write-operations/update-one/arrays.txt | 1181 +++++------------ .../write-operations/update-one/fields.txt | 4 +- .../includes/page-templates/update/arrays.rst | 481 +------ .../includes/page-templates/update/fields.rst | 4 +- .../includes/page-templates/update/update.rst | 2 +- source/usage-examples/updateMany.txt | 2 +- 9 files changed, 645 insertions(+), 1361 deletions(-) diff --git a/source/fundamentals/crud/write-operations.txt b/source/fundamentals/crud/write-operations.txt index a4a25f13..5ca9a5c1 100644 --- a/source/fundamentals/crud/write-operations.txt +++ b/source/fundamentals/crud/write-operations.txt @@ -11,13 +11,15 @@ Write Operations :caption: Write Operations Insert - Update + Update + Update Replace Delete Bulk Write Operations - :ref:`csharp-insert-guide` -- :ref:`csharp-update-documents` +- :ref:`csharp-update-one` +- :ref:`csharp-update-many` - :ref:`csharp-replace-documents` - :ref:`csharp-delete-guide` - :ref:`csharp-bulk-write` diff --git a/source/fundamentals/crud/write-operations/update-many/arrays.txt b/source/fundamentals/crud/write-operations/update-many/arrays.txt index c6cf6d42..f229760f 100644 --- a/source/fundamentals/crud/write-operations/update-many/arrays.txt +++ b/source/fundamentals/crud/write-operations/update-many/arrays.txt @@ -23,54 +23,298 @@ Update Arrays UpdateMany - .. replacement:: file-folder - - update-many - .. replacement:: matching-document-or-documents all matching documents + .. replacement:: update-page-link + + :ref:`` + .. replacement:: push-code-example-tabs - .. tab:: UpdateMany (Sync) - :tabid: update-many-push-sync + .. tabs:: + + .. tab:: UpdateMany (Sync) + :tabid: update-many-push-sync - .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-push - :end-before: // end-update-many-push + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-push + :end-before: // end-update-many-push - .. tab:: UpdateMany (Async) - :tabid: update-many-push-async + .. tab:: UpdateMany (Async) + :tabid: update-many-push-async - .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-push-async - :end-before: // end-update-many-push-async + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-push-async + :end-before: // end-update-many-push-async .. replacement:: addtoset-code-example-tabs - .. tab:: UpdateMany (Sync) - :tabid: update-many-addtoset-sync - - .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-addtoset - :end-before: // end-update-many-addtoset - - .. tab:: UpdateMany (Async) - :tabid: update-many-addtoset-async - - .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-addtoset-async - :end-before: // end-update-many-addtoset-async \ No newline at end of file + .. tabs:: + + .. tab:: UpdateMany (Sync) + :tabid: update-many-addtoset-sync + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-addtoset + :end-before: // end-update-many-addtoset + + .. tab:: UpdateMany (Async) + :tabid: update-many-addtoset-async + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-addtoset-async + :end-before: // end-update-many-addtoset-async + + .. replacement:: pusheach-code-example-tabs + + .. tabs:: + + .. tab:: UpdateMany (Sync) + :tabid: update-many-pusheach-sync + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pusheach + :end-before: // end-update-many-pusheach + + .. tab:: UpdateMany (Async) + :tabid: update-many-pusheach-async + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pusheach-async + :end-before: // end-update-many-pusheach-async + + .. replacement:: addtoseteach-code-example-tabs + + .. tabs:: + + .. tab:: UpdateMany (Sync) + :tabid: update-many-addtoset-sync + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-addtoseteach + :end-before: // end-update-many-addtoseteach + + .. tab:: UpdateMany (Async) + :tabid: update-many-addtoset-async + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-addtoseteach-async + :end-before: // end-update-many-addtoseteach-async + + .. replacement:: popfirst-code-example-tabs + + .. tabs:: + + .. tab:: UpdateMany (Sync) + :tabid: update-many-popfirst-sync + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-popfirst + :end-before: // end-update-many-popfirst + + .. tab:: UpdateMany (Async) + :tabid: update-many-popfirst-async + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-popfirst-async + :end-before: // end-update-many-popfirst-async + + .. replacement:: poplast-code-example-tabs + + .. tabs:: + + .. tab:: UpdateMany (Sync) + :tabid: update-many-poplast-sync + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-poplast + :end-before: // end-update-many-poplast + + .. tab:: UpdateMany (Async) + :tabid: update-many-poplast-async + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-poplast-async + :end-before: // end-update-many-poplast-async + + .. replacement:: pull-code-example-tabs + + .. tabs:: + + .. tab:: UpdateMany (Sync) + :tabid: update-many-pull-sync + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pull + :end-before: // end-update-many-pull + + .. tab:: UpdateMany (Async) + :tabid: update-many-pull-async + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pull-async + :end-before: // end-update-many-pull-async + + .. replacement:: pullall-code-example-tabs + + .. tabs:: + + .. tab:: UpdateMany (Sync) + :tabid: update-many-pullall-sync + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pullall + :end-before: // end-update-many-pullall + + .. tab:: UpdateMany (Async) + :tabid: update-many-pullall-async + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pullall-async + :end-before: // end-update-many-pullall-async + + .. replacement:: pullfilter-code-example-tabs + + .. tabs:: + + .. tab:: UpdateMany (Sync) + :tabid: update-many-pullfilter-sync + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pullfilter + :end-before: // end-update-many-pullfilter + + .. tab:: UpdateMany (Async) + :tabid: update-many-pullfilter-async + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-pullfilter-async + :end-before: // end-update-many-pullfilter-async + + .. replacement:: positional-code-example-tabs + + .. tabs:: + + .. tab:: UpdateMany (Sync) + :tabid: update-many-positional-sync + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-positional + :end-before: // end-update-many-positional + + .. tab:: UpdateMany (Async) + :tabid: update-many-positional-async + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-positional-async + :end-before: // end-update-many-positional-async + + .. replacement:: filteredpositional-code-example-tabs + + .. tabs:: + + .. tab:: UpdateMany (Sync) + :tabid: update-many-filteredpositional-sync + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-filteredpositional + :end-before: // end-update-many-filteredpositional + + .. tab:: UpdateMany (Async) + :tabid: update-many-filteredpositional-async + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-filteredpositional-async + :end-before: // end-update-many-filteredpositional-async + + .. replacement:: allpositional-code-example-tabs + + .. tabs:: + + .. tab:: UpdateMany (Sync) + :tabid: update-many-allpositional-sync + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-allpositional + :end-before: // end-update-many-allpositional + + .. tab:: UpdateMany (Async) + :tabid: update-many-allpositional-async + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-allpositional-async + :end-before: // end-update-many-allpositional-async \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations/update-many/fields.txt b/source/fundamentals/crud/write-operations/update-many/fields.txt index f03c67be..13c9e3a4 100644 --- a/source/fundamentals/crud/write-operations/update-many/fields.txt +++ b/source/fundamentals/crud/write-operations/update-many/fields.txt @@ -23,6 +23,6 @@ Update Fields multiple MongoDB documents - .. replacement:: file-folder + .. replacement:: update-page-link - update-many \ No newline at end of file + :ref:`` \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations/update-one/arrays.txt b/source/fundamentals/crud/write-operations/update-one/arrays.txt index 8577af23..6b63fc00 100644 --- a/source/fundamentals/crud/write-operations/update-one/arrays.txt +++ b/source/fundamentals/crud/write-operations/update-one/arrays.txt @@ -17,883 +17,304 @@ Update Arrays .. meta:: :keywords: synchronous, asynchronous -Overview --------- - -On this page, you can learn how to create ``UpdateDefinition`` objects for array fields. -An ``UpdateDefinition`` object specifies the kind of update operation to perform, the -fields to update, and the new value for each field, if applicable. - -The {+driver-short+} supports the array update operators and modifiers described in the -:manual:`{+mdb-server+} manual `. -To create an ``UpdateDefinition`` object for one of these operators, call the corresponding -method from the ``Builders.Update`` property. -The following sections describe these methods in more detail. - -After you create an ``UpdateDefinition``, pass it to one of the update methods -described on the :ref:`` page. - -.. include:: /includes/method-overloads.rst - -.. include:: /includes/atlas-sample-data.rst - -Add One Value -------------- - -To add one value to the end of an array, call the ``Builders.Update.Push()`` method. -This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to add a value to. - - **Data Type:** ``Expression>>`` - - * - ``value`` - - The value to add to the end of the array field. - - **Data Type:** ``TItem`` - -The following code example uses the ``Push()`` method to add a new ``GradeEntry`` object -to the ``Grades`` array in the matching documents: - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-push-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-push - :end-before: // end-update-one-push - - .. tab:: UpdateOne (Async) - :tabid: update-one-push-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-push-async - :end-before: // end-update-one-push-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-push-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-push - :end-before: // end-update-many-push - - .. tab:: UpdateMany (Async) - :tabid: update-many-push-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-push-async - :end-before: // end-update-many-push-async - -.. tip:: Configure the Push Operation - - To add a value at a specific position in an array, or to sort or slice the array after - updating it, call the ``PushEach()`` method instead. - TODO: link this - -To add one value to the end of an array, *but only if it doesn't already exist in the array*, -call the ``Builders.Update.AddToSet()`` method. -{+mdb-server+} determines whether the value already exists in the array by -comparing the value's BSON representation to the BSON representation of each -other element in the array. - -The ``AddToSet()`` method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to add to. - - **Data Type:** ``Expression>>`` - - * - ``value`` - - The value to add to the end of the array field. - - **Data Type:** ``TItem`` - -The following code example tries to use the ``AddToSet()`` method to re-add the first -``GradeEntry`` object to the ``Grades`` array in the matching documents. Because -the value already exists in the array, the update operation does nothing. - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-addtoset-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-addtoset - :end-before: // end-update-one-addtoset - - .. tab:: UpdateOne (Async) - :tabid: update-one-addtoset-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-addtoset-async - :end-before: // end-update-one-addtoset-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-addtoset-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-addtoset - :end-before: // end-update-many-addtoset - - .. tab:: UpdateMany (Async) - :tabid: update-many-addtoset-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-addtoset-async - :end-before: // end-update-many-addtoset-async - -Add Multiple Values -------------------- - -To add multiple values to an array, call the ``Builders.Update.PushEach()`` method. -This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to add to. - - **Data Type:** ``Expression>>`` - - * - ``values`` - - The values to add to the array field. - - **Data Type:** ``IEnumerable`` - - * - ``slice`` - - The number of elements to keep in the array, counted from the start of the array - after updates. If the value is negative, - the method keeps the specified number of elements from the end of the array. - - **Data Type:** ``int?`` - - * - ``position`` - - The position in the array at which to add the values. By default, the method - adds the values to the end of the array. - - **Data Type:** ``int?`` - - * - ``sort`` - - A ``SortDefinition`` object that specifies how the driver sorts the array elements - after adding the new values. - - **Data Type:** `SortDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.SortDefinition-1.html>`__ - -The following code example uses the ``PushEach()`` method to add two new ``GradeEntry`` -objects to the start of the ``Grades`` array. It then sorts the array elements in -descending order by the values of their ``Score`` fields. - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-pusheach-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pusheach - :end-before: // end-update-one-pusheach - - .. tab:: UpdateOne (Async) - :tabid: update-one-pusheach-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pusheach-async - :end-before: // end-update-one-pusheach-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-pusheach-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pusheach - :end-before: // end-update-many-pusheach - - .. tab:: UpdateMany (Async) - :tabid: update-many-pusheach-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pusheach-async - :end-before: // end-update-many-pusheach-async - -To add multiple values to an array, *but only if they don't already exist in the array*, -call the ``Builders.Update.AddToSetEach()`` method. -This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to add to. - - **Data Type:** ``Expression>>`` - - * - ``values`` - - The values to add to the array field. - - **Data Type:** ``IEnumerable`` - -The following code example tries to use the ``AddToSetEach()`` method to re-add the first -and second ``GradeEntry`` objects to the ``Grades`` array in the matching documents. -Because these values already exist in the array, the update operation does nothing. - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-addtoseteach-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-addtoseteach - :end-before: // end-update-one-addtoseteach - - .. tab:: UpdateOne (Async) - :tabid: update-one-addtoseteach-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-addtoseteach-async - :end-before: // end-update-one-addtoseteach-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-addtoset-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-addtoseteach - :end-before: // end-update-many-addtoseteach - - .. tab:: UpdateMany (Async) - :tabid: update-many-addtoset-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-addtoseteach-async - :end-before: // end-update-many-addtoseteach-async - -Remove Values -------------- - -To remove the first value from an array, call the ``Builders.Update.PopFirst()`` method. -This method accepts the following parameter: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to remove the first value from. - - **Data Type:** ``Expression>>`` - -The following code example uses the ``PopFirst()`` method to remove the first ``GradeEntry`` -object from the ``Grades`` array in the matching documents: - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-popfirst-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-popfirst - :end-before: // end-update-one-popfirst - - .. tab:: UpdateOne (Async) - :tabid: update-one-popfirst-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-popfirst-async - :end-before: // end-update-one-popfirst-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-popfirst-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-popfirst - :end-before: // end-update-many-popfirst - - .. tab:: UpdateMany (Async) - :tabid: update-many-popfirst-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-popfirst-async - :end-before: // end-update-many-popfirst-async - -To remove the last value from an array, call the ``Builders.Update.PopLast()`` method: -This method accepts the following parameter: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to remove the last value from. - - **Data Type:** ``Expression>>`` - -The following code example uses the ``PopLast()`` method to remove the last ``GradeEntry`` -object from the ``Grades`` array in the matching documents: - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-poplast-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-poplast - :end-before: // end-update-one-poplast - - .. tab:: UpdateOne (Async) - :tabid: update-one-poplast-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-poplast-async - :end-before: // end-update-one-poplast-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-poplast-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-poplast - :end-before: // end-update-many-poplast - - .. tab:: UpdateMany (Async) - :tabid: update-many-poplast-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-poplast-async - :end-before: // end-update-many-poplast-async - -To remove all instances of a specific value from an array, call the ``Builders.Update.Pull()`` method: -This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to add to. - - **Data Type:** ``Expression>>`` - - * - ``value`` - - The value to remove from the array field. - - **Data Type:** ``IEnumerable`` - -The following code example uses the ``Pull()`` method to remove all instances of a -a specific ``GradeEntry`` object from the ``Grades`` array in the matching documents: - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-pull-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pull - :end-before: // end-update-one-pull - - .. tab:: UpdateOne (Async) - :tabid: update-one-pull-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pull-async - :end-before: // end-update-one-pull-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-pull-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pull - :end-before: // end-update-many-pull - - .. tab:: UpdateMany (Async) - :tabid: update-many-pull-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pull-async - :end-before: // end-update-many-pull-async - -To remove all instances of more than one specific value from an array, call the -``Builders.Update.PullAll()`` method. -This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to add to. - - **Data Type:** ``Expression>>`` - - * - ``values`` - - The values to remove from the array field. - - **Data Type:** ``IEnumerable`` - -The following code example uses the ``PullAll()`` method to remove all instances of two -specific ``GradeEntry`` objects from the ``Grades`` array in the matching documents: - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-pullall-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pullall - :end-before: // end-update-one-pullall - - .. tab:: UpdateOne (Async) - :tabid: update-one-pullall-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pullall-async - :end-before: // end-update-one-pullall-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-pullall-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pullall - :end-before: // end-update-many-pullall - - .. tab:: UpdateMany (Async) - :tabid: update-many-pullall-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pullall-async - :end-before: // end-update-many-pullall-async - -To remove all values that match a specific condition from an array, call the -``Builders.Update.PullFilter()`` method. -This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to add to. - - **Data Type:** ``Expression>>`` - - * - ``filter`` - - A query filter that specifies the condition for values to remove. - - **Data Type:** `FilterDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ - -The following code example uses the ``PullFilter()`` method to remove all ``GradeEntry`` -objects where the ``Grade`` property is ``"F"`` from the ``Grades`` array in the -matching documents: - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-pullfilter-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pullfilter - :end-before: // end-update-one-pullfilter - - .. tab:: UpdateOne (Async) - :tabid: update-one-pullfilter-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pullfilter-async - :end-before: // end-update-one-pullfilter-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-pullfilter-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pullfilter - :end-before: // end-update-many-pullfilter - - .. tab:: UpdateMany (Async) - :tabid: update-many-pullfilter-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pullfilter-async - :end-before: // end-update-many-pullfilter-async - -Update Matching Values ----------------------- - -To update a value in an array field, call the ``Builders.Update.Set()`` method. -This method accepts the following parameters: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Parameter - - Description - - * - ``field`` - - An expression that specifies the array field to update. - - **Data Type:** ``Expression>>`` - - * - ``value`` - - The new value to set in the array field. - - **Data Type:** ``TItem`` - -You can use the -:manual:`positional operator ` -in combination with the ``Set()`` method to query and update specific values in the array. -The following sections describe different ways to use the positional operator. - -First Matching Value -~~~~~~~~~~~~~~~~~~~~ - -To update only the first value in an array that matches a query filter, use the positional operator -(``$``) in combination with the ``Set()`` method. - -.. note:: - - To use the positional operator, the array field must be part of the query filter. - -The following example uses the ``Set()`` method and the positional operator to -update the ``Grades`` array in all documents that match the query filter. First, -it finds *only the first* ``GradeEntry`` object in the ``Grades`` array where the ``Grade`` property -has the value ``"A"``. Then, it updates the ``Score`` property of the first matching -``GradeEntry`` object to 100. - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-positional-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-positional - :end-before: // end-update-one-positional - - .. tab:: UpdateOne (Async) - :tabid: update-one-positional-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-positional-async - :end-before: // end-update-one-positional-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-positional-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-positional - :end-before: // end-update-many-positional - - .. tab:: UpdateMany (Async) - :tabid: update-many-positional-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-positional-async - :end-before: // end-update-many-positional-async - -All Matching Values -~~~~~~~~~~~~~~~~~~~ - -To update all values in an array that match a specified condition, use the filtered -positional operator (``$[]``) in combination with the ``Set()`` method. - -The following example uses the ``Set()`` method and the filtered positional operator -to update the ``Score`` property of all matching -``GradeEntry`` objects in the Grades`` array to 100 in all documents that match the -query filter. - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-allpositional-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-allpositional - :end-before: // end-update-one-allpositional - - .. tab:: UpdateOne (Async) - :tabid: update-one-allpositional-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-allpositional-async - :end-before: // end-update-one-allpositional-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-allpositional-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-allpositional - :end-before: // end-update-many-allpositional - - .. tab:: UpdateMany (Async) - :tabid: update-many-allpositional-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-allpositional-async - :end-before: // end-update-many-allpositional-async - -All Values -~~~~~~~~~~ - -To update all values in an array that match a query filter, use the all-positional operator -(``$[]``) in combination with the ``Set()`` method. - -The following example uses the ``Set()`` method and the all-positional operator -to update the ``Score`` property of all ``GradeEntry`` objects in the Grades`` array -to 100 in all documents that match the query filter. - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-filteredpositional-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-filteredpositional - :end-before: // end-update-one-filteredpositional - - .. tab:: UpdateOne (Async) - :tabid: update-one-filteredpositional-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-filteredpositional-async - :end-before: // end-update-one-filteredpositional-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-filteredpositional-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-filteredpositional - :end-before: // end-update-many-filteredpositional - - .. tab:: UpdateMany (Async) - :tabid: update-many-filteredpositional-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-filteredpositional-async - :end-before: // end-update-many-filteredpositional-async - - -LINQ3 Provider -~~~~~~~~~~~~~~ - -LINQ syntax contains a positional operator (``$``) that you can use to update elements in an array field. -Previous versions of the {+driver-short+} supported both the LINQ2 and LINQ3 providers. -In LINQ2, you could use ``-1`` to indicate use of the positional operator. - -For example, the ``Restaurant`` class contains an array field named ``Grades`` that -contains multiple ``GradeEntry`` elements. If your application were using the LINQ2 -provider, you could use the following code sample to update the -``Grade`` field of the first element in this array: - -.. code-block:: csharp - :linenos: - - var anArrayId = ObjectId.GenerateNewId(); - var another = new Restaurant - { - Id = ObjectId.GenerateNewId(), - AnArrayMember = new List - { - new AnArrayClass { Id = anArrayId, Deleted = false } - } - }; - - await collection.UpdateOneAsync( - r => r.Id == "targetId" && r.AnArrayMember.Any(l => l.Id == anArrayId), - Builders.Update.Set(l => l.AnArrayMember.ElementAt(-1).Deleted, true)); - -.. code-block:: csharp - :linenos: - - var anArrayId = ObjectId.GenerateNewId(); - var another = new Restaurant - { - Id = ObjectId.GenerateNewId(), - AnArrayMember = new List - { - new AnArrayClass { Id = anArrayId, Deleted = false } - } - }; - - await collection.UpdateOneAsync( - r => r.Id == "targetId" && r.AnArrayMember.Any(l => l.Id == anArrayId), - Builders.Update.Set(l => l.AnArrayMember.ElementAt(-1).Deleted, true)); - -This no longer works in LINQ3. Instead, you must use the following syntax: +.. include:: /includes/page-templates/update/arrays.rst + + .. replacement:: sync-method + + UpdateOne + + .. replacement:: matching-document-or-documents + + the matching document + + .. replacement:: update-page-link + + :ref:`` + + .. replacement:: push-code-example-tabs + + .. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-push-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-push + :end-before: // end-update-one-push + + .. tab:: UpdateOne (Async) + :tabid: update-one-push-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-push-async + :end-before: // end-update-one-push-async + + .. replacement:: addtoset-code-example-tabs + + .. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-addtoset-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-addtoset + :end-before: // end-update-one-addtoset + + .. tab:: UpdateOne (Async) + :tabid: update-one-addtoset-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-addtoset-async + :end-before: // end-update-one-addtoset-async + + .. replacement:: pusheach-code-example-tabs + + .. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-pusheach-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pusheach + :end-before: // end-update-one-pusheach + + .. tab:: UpdateOne (Async) + :tabid: update-one-pusheach-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pusheach-async + :end-before: // end-update-one-pusheach-async + + .. replacement:: addtoseteach-code-example-tabs + + .. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-addtoset-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-addtoseteach + :end-before: // end-update-one-addtoseteach + + .. tab:: UpdateOne (Async) + :tabid: update-one-addtoset-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-addtoseteach-async + :end-before: // end-update-one-addtoseteach-async + + .. replacement:: popfirst-code-example-tabs + + .. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-popfirst-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-popfirst + :end-before: // end-update-one-popfirst + + .. tab:: UpdateOne (Async) + :tabid: update-one-popfirst-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-popfirst-async + :end-before: // end-update-one-popfirst-async + + .. replacement:: poplast-code-example-tabs + + .. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-poplast-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-poplast + :end-before: // end-update-one-poplast + + .. tab:: UpdateOne (Async) + :tabid: update-one-poplast-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-poplast-async + :end-before: // end-update-one-poplast-async + + .. replacement:: pull-code-example-tabs + + .. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-pull-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pull + :end-before: // end-update-one-pull + + .. tab:: UpdateOne (Async) + :tabid: update-one-pull-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pull-async + :end-before: // end-update-one-pull-async + + .. replacement:: pullall-code-example-tabs + + .. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-pullall-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pullall + :end-before: // end-update-one-pullall + + .. tab:: UpdateOne (Async) + :tabid: update-one-pullall-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pullall-async + :end-before: // end-update-one-pullall-async + + .. replacement:: pullfilter-code-example-tabs + + .. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-pullfilter-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pullfilter + :end-before: // end-update-one-pullfilter + + .. tab:: UpdateOne (Async) + :tabid: update-one-pullfilter-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-pullfilter-async + :end-before: // end-update-one-pullfilter-async + + .. replacement:: positional-code-example-tabs + + .. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-positional-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-positional + :end-before: // end-update-one-positional + + .. tab:: UpdateOne (Async) + :tabid: update-one-positional-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-positional-async + :end-before: // end-update-one-positional-async + + .. replacement:: filteredpositional-code-example-tabs + + .. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-filteredpositional-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-filteredpositional + :end-before: // end-update-one-filteredpositional + + .. tab:: UpdateOne (Async) + :tabid: update-one-filteredpositional-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-filteredpositional-async + :end-before: // end-update-one-filteredpositional-async + + .. replacement:: allpositional-code-example-tabs + + .. tabs:: + + .. tab:: UpdateOne (Sync) + :tabid: update-one-allpositional-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-allpositional + :end-before: // end-update-one-allpositional + + .. tab:: UpdateOne (Async) + :tabid: update-one-allpositional-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-allpositional-async + :end-before: // end-update-one-allpositional-async \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations/update-one/fields.txt b/source/fundamentals/crud/write-operations/update-one/fields.txt index 575f795c..0f89433e 100644 --- a/source/fundamentals/crud/write-operations/update-one/fields.txt +++ b/source/fundamentals/crud/write-operations/update-one/fields.txt @@ -23,6 +23,6 @@ Update Fields one MongoDB document - .. replacement:: file-folder + .. replacement:: update-page-link - update-one \ No newline at end of file + :ref:`` \ No newline at end of file diff --git a/source/includes/page-templates/update/arrays.rst b/source/includes/page-templates/update/arrays.rst index ad32b913..6bb454a9 100644 --- a/source/includes/page-templates/update/arrays.rst +++ b/source/includes/page-templates/update/arrays.rst @@ -13,7 +13,7 @@ The following sections describe these methods in more detail. After you create an ``UpdateDefinition`` object, pass it to the ``|sync-method|()`` or ``|sync-method|Async()`` method. For more information about these methods, see -the :ref:`` page. +the |update-page-link| page. .. include:: /includes/method-overloads.rst @@ -81,6 +81,8 @@ The following code example calls the ``AddToSet()`` method to re-add the first ``GradeEntry`` object to the ``Grades`` array in |matching-document-or-documents|. Because the value already exists in the array, the update operation does nothing. +|addtoset-code-example-tabs| + Add Multiple Values ------------------- @@ -124,50 +126,10 @@ This method accepts the following parameters: **Data Type:** `SortDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.SortDefinition-1.html>`__ The following code example uses the ``PushEach()`` method to add two new ``GradeEntry`` -objects to the start of the ``Grades`` array. It then sorts the array elements in -descending order by the values of their ``Score`` fields. - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-pusheach-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pusheach - :end-before: // end-update-one-pusheach - - .. tab:: UpdateOne (Async) - :tabid: update-one-pusheach-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pusheach-async - :end-before: // end-update-one-pusheach-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-pusheach-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pusheach - :end-before: // end-update-many-pusheach - - .. tab:: UpdateMany (Async) - :tabid: update-many-pusheach-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pusheach-async - :end-before: // end-update-many-pusheach-async +objects to the start of the ``Grades`` array in |matching-document-or-documents|. +It then sorts the array elements in descending order by the values of their ``Score`` fields. + +|pusheach-code-example-tabs| To add multiple values to an array, *but only if they don't already exist in the array*, call the ``Builders.Update.AddToSetEach()`` method. @@ -190,51 +152,11 @@ This method accepts the following parameters: **Data Type:** ``IEnumerable`` -The following code example tries to use the ``AddToSetEach()`` method to re-add the first +The following code example calls the ``AddToSetEach()`` method to re-add the first and second ``GradeEntry`` objects to the ``Grades`` array in |matching-document-or-documents|. Because these values already exist in the array, the update operation does nothing. -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-addtoseteach-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-addtoseteach - :end-before: // end-update-one-addtoseteach - - .. tab:: UpdateOne (Async) - :tabid: update-one-addtoseteach-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-addtoseteach-async - :end-before: // end-update-one-addtoseteach-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-addtoset-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-addtoseteach - :end-before: // end-update-many-addtoseteach - - .. tab:: UpdateMany (Async) - :tabid: update-many-addtoset-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-addtoseteach-async - :end-before: // end-update-many-addtoseteach-async +|addtoseteach-code-example-tabs| Remove Values ------------- @@ -257,47 +179,7 @@ This method accepts the following parameter: The following code example uses the ``PopFirst()`` method to remove the first ``GradeEntry`` object from the ``Grades`` array in |matching-document-or-documents|: -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-popfirst-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-popfirst - :end-before: // end-update-one-popfirst - - .. tab:: UpdateOne (Async) - :tabid: update-one-popfirst-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-popfirst-async - :end-before: // end-update-one-popfirst-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-popfirst-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-popfirst - :end-before: // end-update-many-popfirst - - .. tab:: UpdateMany (Async) - :tabid: update-many-popfirst-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-popfirst-async - :end-before: // end-update-many-popfirst-async +|popfirst-code-example-tabs| To remove the last value from an array, call the ``Builders.Update.PopLast()`` method: This method accepts the following parameter: @@ -317,50 +199,10 @@ This method accepts the following parameter: The following code example uses the ``PopLast()`` method to remove the last ``GradeEntry`` object from the ``Grades`` array in |matching-document-or-documents|: -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-poplast-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-poplast - :end-before: // end-update-one-poplast - - .. tab:: UpdateOne (Async) - :tabid: update-one-poplast-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-poplast-async - :end-before: // end-update-one-poplast-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-poplast-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-poplast - :end-before: // end-update-many-poplast - - .. tab:: UpdateMany (Async) - :tabid: update-many-poplast-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-poplast-async - :end-before: // end-update-many-poplast-async - -To remove all instances of a specific value from an array, call the ``Builders.Update.Pull()`` method: -This method accepts the following parameters: +|poplast-code-example-tabs| + +To remove all instances of a specific value from an array, call the +``Builders.Update.Pull()`` method. This method accepts the following parameters: .. list-table:: :widths: 30 70 @@ -370,7 +212,7 @@ This method accepts the following parameters: - Description * - ``field`` - - An expression that specifies the array field to add to. + - An expression that specifies the array field to remove the values from. **Data Type:** ``Expression>>`` @@ -382,47 +224,7 @@ This method accepts the following parameters: The following code example uses the ``Pull()`` method to remove all instances of a a specific ``GradeEntry`` object from the ``Grades`` array in |matching-document-or-documents|: -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-pull-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pull - :end-before: // end-update-one-pull - - .. tab:: UpdateOne (Async) - :tabid: update-one-pull-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pull-async - :end-before: // end-update-one-pull-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-pull-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pull - :end-before: // end-update-many-pull - - .. tab:: UpdateMany (Async) - :tabid: update-many-pull-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pull-async - :end-before: // end-update-many-pull-async +|pull-code-example-tabs| To remove all instances of more than one specific value from an array, call the ``Builders.Update.PullAll()`` method. @@ -436,7 +238,7 @@ This method accepts the following parameters: - Description * - ``field`` - - An expression that specifies the array field to add to. + - An expression that specifies the array field to remove the values from. **Data Type:** ``Expression>>`` @@ -448,47 +250,7 @@ This method accepts the following parameters: The following code example uses the ``PullAll()`` method to remove all instances of two specific ``GradeEntry`` objects from the ``Grades`` array in |matching-document-or-documents|: -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-pullall-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pullall - :end-before: // end-update-one-pullall - - .. tab:: UpdateOne (Async) - :tabid: update-one-pullall-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pullall-async - :end-before: // end-update-one-pullall-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-pullall-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pullall - :end-before: // end-update-many-pullall - - .. tab:: UpdateMany (Async) - :tabid: update-many-pullall-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pullall-async - :end-before: // end-update-many-pullall-async +|pullall-code-example-tabs| To remove all values that match a specific condition from an array, call the ``Builders.Update.PullFilter()`` method. @@ -502,7 +264,7 @@ This method accepts the following parameters: - Description * - ``field`` - - An expression that specifies the array field to add to. + - An expression that specifies the array field to remove the values from. **Data Type:** ``Expression>>`` @@ -512,50 +274,10 @@ This method accepts the following parameters: **Data Type:** `FilterDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ The following code example uses the ``PullFilter()`` method to remove all ``GradeEntry`` -objects where the ``Grade`` property is ``"F"`` from the ``Grades`` array in the +objects where the ``Grade`` value is ``"F"`` from the ``Grades`` array in the matching documents: -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-pullfilter-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pullfilter - :end-before: // end-update-one-pullfilter - - .. tab:: UpdateOne (Async) - :tabid: update-one-pullfilter-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-pullfilter-async - :end-before: // end-update-one-pullfilter-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-pullfilter-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pullfilter - :end-before: // end-update-many-pullfilter - - .. tab:: UpdateMany (Async) - :tabid: update-many-pullfilter-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-pullfilter-async - :end-before: // end-update-many-pullfilter-async +|pullfilter-code-example-tabs| Update Matching Values ---------------------- @@ -576,7 +298,7 @@ This method accepts the following parameters: **Data Type:** ``Expression>>`` * - ``value`` - - The new value to set in the array field. + - The new value to set into the array field. **Data Type:** ``TItem`` @@ -588,60 +310,20 @@ The following sections describe different ways to use the positional operator. First Matching Value ~~~~~~~~~~~~~~~~~~~~ -To update only the first value in an array that matches a query filter, use the positional operator -(``$``) in combination with the ``Set()`` method. +To update only the first value in an array that matches a query filter, use the +positional operator (``$``) in combination with the ``Set()`` method. .. note:: To use the positional operator, the array field must be part of the query filter. The following example uses the ``Set()`` method and the positional operator to -update the ``Grades`` array in all documents that match the query filter. First, +update the ``Grades`` array in |matching-document-or-documents|. First, it finds *only the first* ``GradeEntry`` object in the ``Grades`` array where the ``Grade`` property has the value ``"A"``. Then, it updates the ``Score`` property of the first matching ``GradeEntry`` object to 100. -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-positional-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-positional - :end-before: // end-update-one-positional - - .. tab:: UpdateOne (Async) - :tabid: update-one-positional-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-positional-async - :end-before: // end-update-one-positional-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-positional-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-positional - :end-before: // end-update-many-positional - - .. tab:: UpdateMany (Async) - :tabid: update-many-positional-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-positional-async - :end-before: // end-update-many-positional-async +|positional-code-example-tabs| All Matching Values ~~~~~~~~~~~~~~~~~~~ @@ -651,50 +333,9 @@ positional operator (``$[]``) in combination with the ``Set()`` meth The following example uses the ``Set()`` method and the filtered positional operator to update the ``Score`` property of all matching -``GradeEntry`` objects in the Grades`` array to 100 in all documents that match the -query filter. - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-allpositional-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-allpositional - :end-before: // end-update-one-allpositional - - .. tab:: UpdateOne (Async) - :tabid: update-one-allpositional-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-allpositional-async - :end-before: // end-update-one-allpositional-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-allpositional-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-allpositional - :end-before: // end-update-many-allpositional - - .. tab:: UpdateMany (Async) - :tabid: update-many-allpositional-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-allpositional-async - :end-before: // end-update-many-allpositional-async +``GradeEntry`` objects in the Grades`` array to 100 in |matching-document-or-documents|: + +|filteredpositional-code-example-tabs| All Values ~~~~~~~~~~ @@ -704,50 +345,9 @@ To update all values in an array that match a query filter, use the all-position The following example uses the ``Set()`` method and the all-positional operator to update the ``Score`` property of all ``GradeEntry`` objects in the Grades`` array -to 100 in all documents that match the query filter. - -.. tabs:: - - .. tab:: UpdateOne (Sync) - :tabid: update-one-filteredpositional-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-filteredpositional - :end-before: // end-update-one-filteredpositional - - .. tab:: UpdateOne (Async) - :tabid: update-one-filteredpositional-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-one-filteredpositional-async - :end-before: // end-update-one-filteredpositional-async - - .. tab:: UpdateMany (Sync) - :tabid: update-many-filteredpositional-sync - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-filteredpositional - :end-before: // end-update-many-filteredpositional - - .. tab:: UpdateMany (Async) - :tabid: update-many-filteredpositional-async - - .. literalinclude:: /includes/code-examples/UpdateArrays.cs - :language: csharp - :copyable: true - :dedent: - :start-after: // start-update-many-filteredpositional-async - :end-before: // end-update-many-filteredpositional-async +to 100 in |matching-document-or-documents|: +|allpositional-code-example-tabs| LINQ3 Provider ~~~~~~~~~~~~~~ @@ -795,4 +395,21 @@ provider, you could use the following code sample to update the r => r.Id == "targetId" && r.AnArrayMember.Any(l => l.Id == anArrayId), Builders.Update.Set(l => l.AnArrayMember.ElementAt(-1).Deleted, true)); -This no longer works in LINQ3. Instead, you must use the following syntax: \ No newline at end of file +This no longer works in LINQ3. Instead, you must use the following syntax: + +API Documentation +----------------- + +For more information about any of the methods or types discussed in this +guide, see the following API documentation: + +- `Builders.Update.Push() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionBuilder-1.Push.html>`__ +- `Builders.Update.AddToSet() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionBuilder-1.AddToSet.html>`__ +- `Builders.Update.PushEach() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionBuilder-1.PushEach.html>`__ +- `Builders.Update.AddToSetEach() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionBuilder-1.AddToSetEach.html>`__ +- `Builders.Update.PopFirst() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionBuilder-1.PopFirst.html>`__ +- `Builders.Update.PopLast() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionBuilder-1.PopLast.html>`__ +- `Builders.Update.Pull() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionBuilder-1.Pull.html>`__ +- `Builders.Update.PullAll() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionBuilder-1.PullAll.html>`__ +- `Builders.Update.PullFilter() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionBuilder-1.PullFilter.html>`__ +- `Builders.Update.Set() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionBuilder-1.Set.html>`__ \ No newline at end of file diff --git a/source/includes/page-templates/update/fields.rst b/source/includes/page-templates/update/fields.rst index 9126256c..b1fb1f1a 100644 --- a/source/includes/page-templates/update/fields.rst +++ b/source/includes/page-templates/update/fields.rst @@ -4,8 +4,8 @@ Overview On this page, you can learn how to use the {+driver-long+} to update fields in |one-or-multiple|. This page describes how to create ``UpdateDefinition`` objects that specify the update operations you want to perform on fields. -You can pass these objects to the update methods described on the -:ref:`` page. +You can pass these objects to the update methods described on the |update-page-link| +page. The {+driver-short+} supports the field update operators described in the :manual:`{+mdb-server+} manual `. To specify an diff --git a/source/includes/page-templates/update/update.rst b/source/includes/page-templates/update/update.rst index f65b18f2..99bfc6ee 100644 --- a/source/includes/page-templates/update/update.rst +++ b/source/includes/page-templates/update/update.rst @@ -124,7 +124,7 @@ The following code example uses the ``Pipeline()`` method to combine a :manual:`$unset ` operation: -|pipeline-code-example-tabs +|pipeline-code-example-tabs| .. note:: Unsupported Operations diff --git a/source/usage-examples/updateMany.txt b/source/usage-examples/updateMany.txt index 65a2763e..5d9b227b 100644 --- a/source/usage-examples/updateMany.txt +++ b/source/usage-examples/updateMany.txt @@ -1,4 +1,4 @@ -.. _csharp-update-many: +.. _csharp-examples-update-many: ===================== Update Many Documents From f6c746420d61af9f60726c9d89d6e6375d7a9252 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Tue, 26 Nov 2024 11:39:28 -0600 Subject: [PATCH 23/39] wip --- config/redirects | 1 + .../crud/write-operations/update-many.txt | 4 +- .../write-operations/update-many/arrays.txt | 84 ++++++- .../crud/write-operations/update-one.txt | 4 +- .../write-operations/update-one/arrays.txt | 80 +++++- .../update-many/UpdateManyArrays.cs | 230 +++++++++++++----- .../update-one/UpdateOneArrays.cs | 115 +++++++++ .../includes/page-templates/update/arrays.rst | 9 +- .../includes/page-templates/update/update.rst | 12 +- 9 files changed, 450 insertions(+), 89 deletions(-) diff --git a/config/redirects b/config/redirects index 6234d6cb..421db29e 100644 --- a/config/redirects +++ b/config/redirects @@ -18,3 +18,4 @@ raw: ${prefix}/master -> ${base}/upcoming/ [*-v2.30]: ${prefix}/${version}/upgrade/v3/ -> ${base}/${version}/upgrade/ [*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/modify/#replace-operation -> ${base}/${version}/fundamentals/crud/write-operations/replace/ [*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/modify/ -> ${base}/${version}/fundamentals/crud/write-operations/ +[*-master] ${prefix}/${version}/fundamentals/builders/#define-an-update -> ${base}/${version}/fundamentals/crud/write-operations diff --git a/source/fundamentals/crud/write-operations/update-many.txt b/source/fundamentals/crud/write-operations/update-many.txt index e5756442..258d22e8 100644 --- a/source/fundamentals/crud/write-operations/update-many.txt +++ b/source/fundamentals/crud/write-operations/update-many.txt @@ -28,11 +28,11 @@ Update Many .. replacement:: sync-method - UpdateMany + ``UpdateMany()`` .. replacement:: async-method - UpdateManyAsync + ``UpdateManyAsync()`` .. replacement:: document-or-documents diff --git a/source/fundamentals/crud/write-operations/update-many/arrays.txt b/source/fundamentals/crud/write-operations/update-many/arrays.txt index f229760f..51b1d7c6 100644 --- a/source/fundamentals/crud/write-operations/update-many/arrays.txt +++ b/source/fundamentals/crud/write-operations/update-many/arrays.txt @@ -21,7 +21,11 @@ Update Arrays .. replacement:: sync-method - UpdateMany + ``UpdateMany()`` + + .. replacement:: async-method + + ``UpdateManyAsync()`` .. replacement:: matching-document-or-documents @@ -251,7 +255,7 @@ Update Arrays .. tabs:: - .. tab:: UpdateMany (Sync) + .. tab:: Positional Operator (Sync) :tabid: update-many-positional-sync .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -261,7 +265,7 @@ Update Arrays :start-after: // start-update-many-positional :end-before: // end-update-many-positional - .. tab:: UpdateMany (Async) + .. tab:: Positional Operator (Async) :tabid: update-many-positional-async .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -271,11 +275,31 @@ Update Arrays :start-after: // start-update-many-positional-async :end-before: // end-update-many-positional-async + .. tab:: LINQ (Sync) + :tabid: update-many-positional-linq-sync + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-positional-linq + :end-before: // end-update-many-positional-linq + + .. tab:: LINQ (Async) + :tabid: update-many-positional-linq-async + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-positional-linq-async + :end-before: // end-update-many-positional-linq-async + .. replacement:: filteredpositional-code-example-tabs .. tabs:: - .. tab:: UpdateMany (Sync) + .. tab:: Positional Operator (Sync) :tabid: update-many-filteredpositional-sync .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -285,21 +309,41 @@ Update Arrays :start-after: // start-update-many-filteredpositional :end-before: // end-update-many-filteredpositional - .. tab:: UpdateMany (Async) + .. tab:: Positional Operator (Async) :tabid: update-many-filteredpositional-async .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp :copyable: true :dedent: - :start-after: // start-update-many-filteredpositional-async - :end-before: // end-update-many-filteredpositional-async + :start-after: // start-update-many-filteredpositional + :end-before: // end-update-many-filteredpositional + + .. tab:: LINQ (Sync) + :tabid: update-many-filteredpositional-linq-sync + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-filteredpositional-linq + :end-before: // end-update-many-filteredpositional-linq + + .. tab:: LINQ (Async) + :tabid: update-many-filteredpositional-linq-async + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-filteredpositional-linq-async + :end-before: // end-update-many-filteredpositional-linq-async .. replacement:: allpositional-code-example-tabs .. tabs:: - .. tab:: UpdateMany (Sync) + .. tab:: Positional Operator (Sync) :tabid: update-many-allpositional-sync .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -309,7 +353,7 @@ Update Arrays :start-after: // start-update-many-allpositional :end-before: // end-update-many-allpositional - .. tab:: UpdateMany (Async) + .. tab:: Positional Operator (Async) :tabid: update-many-allpositional-async .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -317,4 +361,24 @@ Update Arrays :copyable: true :dedent: :start-after: // start-update-many-allpositional-async - :end-before: // end-update-many-allpositional-async \ No newline at end of file + :end-before: // end-update-many-allpositional-async + + .. tab:: LINQ (Sync) + :tabid: update-many-allpositional-linq-sync + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-allpositional-linq + :end-before: // end-update-many-allpositional-linq + + .. tab:: LINQ (Async) + :tabid: update-many-allpositional-linq-async + + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-many-allpositional-linq-async + :end-before: // end-update-many-allpositional-linq-async \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations/update-one.txt b/source/fundamentals/crud/write-operations/update-one.txt index 27e96422..ed3594db 100644 --- a/source/fundamentals/crud/write-operations/update-one.txt +++ b/source/fundamentals/crud/write-operations/update-one.txt @@ -28,11 +28,11 @@ Update One .. replacement:: sync-method - UpdateOne + ``UpdateOne()`` .. replacement:: async-method - UpdateOneAsync + ``UpdateOneAsync()`` .. replacement:: document-or-documents diff --git a/source/fundamentals/crud/write-operations/update-one/arrays.txt b/source/fundamentals/crud/write-operations/update-one/arrays.txt index 6b63fc00..90b0b028 100644 --- a/source/fundamentals/crud/write-operations/update-one/arrays.txt +++ b/source/fundamentals/crud/write-operations/update-one/arrays.txt @@ -21,7 +21,11 @@ Update Arrays .. replacement:: sync-method - UpdateOne + ``UpdateOne()`` + + .. replacement:: async-method + + ``UpdateOneAsync()`` .. replacement:: matching-document-or-documents @@ -251,7 +255,7 @@ Update Arrays .. tabs:: - .. tab:: UpdateOne (Sync) + .. tab:: Positional Operator (Sync) :tabid: update-one-positional-sync .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -261,7 +265,7 @@ Update Arrays :start-after: // start-update-one-positional :end-before: // end-update-one-positional - .. tab:: UpdateOne (Async) + .. tab:: Positional Operator (Async) :tabid: update-one-positional-async .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -271,11 +275,31 @@ Update Arrays :start-after: // start-update-one-positional-async :end-before: // end-update-one-positional-async + .. tab:: LINQ (Sync) + :tabid: update-one-positional-linq-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-positional-linq + :end-before: // end-update-one-positional-linq + + .. tab:: LINQ (Async) + :tabid: update-one-positional-linq-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-positional-linq-async + :end-before: // end-update-one-positional-linq-async + .. replacement:: filteredpositional-code-example-tabs .. tabs:: - .. tab:: UpdateOne (Sync) + .. tab:: Positional Operator (Sync) :tabid: update-one-filteredpositional-sync .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -285,7 +309,7 @@ Update Arrays :start-after: // start-update-one-filteredpositional :end-before: // end-update-one-filteredpositional - .. tab:: UpdateOne (Async) + .. tab:: Positional Operator (Async) :tabid: update-one-filteredpositional-async .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -295,11 +319,31 @@ Update Arrays :start-after: // start-update-one-filteredpositional-async :end-before: // end-update-one-filteredpositional-async + .. tab:: LINQ (Sync) + :tabid: update-one-filteredpositional-linq-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-filteredpositional-linq + :end-before: // end-update-one-filteredpositional-linq + + .. tab:: LINQ (Async) + :tabid: update-one-filteredpositional-linq-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-filteredpositional-linq-async + :end-before: // end-update-one-filteredpositional-linq-async + .. replacement:: allpositional-code-example-tabs .. tabs:: - .. tab:: UpdateOne (Sync) + .. tab:: Positional Operator (Sync) :tabid: update-one-allpositional-sync .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -309,7 +353,7 @@ Update Arrays :start-after: // start-update-one-allpositional :end-before: // end-update-one-allpositional - .. tab:: UpdateOne (Async) + .. tab:: Positional Operator (Async) :tabid: update-one-allpositional-async .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -317,4 +361,24 @@ Update Arrays :copyable: true :dedent: :start-after: // start-update-one-allpositional-async - :end-before: // end-update-one-allpositional-async \ No newline at end of file + :end-before: // end-update-one-allpositional-async + + .. tab:: LINQ (Sync) + :tabid: update-one-allpositional-linq-sync + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-allpositional-linq + :end-before: // end-update-one-allpositional-linq + + .. tab:: LINQ (Async) + :tabid: update-one-allpositional-linq-async + + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs + :language: csharp + :copyable: true + :dedent: + :start-after: // start-update-one-allpositional-linq-async + :end-before: // end-update-one-allpositional-linq-async \ No newline at end of file diff --git a/source/includes/code-examples/update-many/UpdateManyArrays.cs b/source/includes/code-examples/update-many/UpdateManyArrays.cs index 720f913b..5f6c98f8 100644 --- a/source/includes/code-examples/update-many/UpdateManyArrays.cs +++ b/source/includes/code-examples/update-many/UpdateManyArrays.cs @@ -1,6 +1,7 @@ using MongoDB.Bson; using MongoDB.Bson.Serialization.Conventions; using MongoDB.Driver; +using MongoDB.Driver.Linq; using WriteData.Models; namespace CSharpExamples.WriteData; @@ -103,10 +104,10 @@ public static UpdateResult UpdateManyPushEach() .Eq("name", "Downtown Deli"); var newGrades = new List - { - new GradeEntry { Date = DateTime.Now, Grade = "A", Score = 95 }, - new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89,} - }; + { + new GradeEntry { Date = DateTime.Now, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89, } + }; var scoreSort = Builders.Sort.Descending(g => g.Score); @@ -129,10 +130,10 @@ public static async Task UpdateManyPushEachAsync() .Eq("name", "Downtown Deli"); var newGrades = new List - { - new GradeEntry { Date = DateTime.Now, Grade = "A", Score = 95 }, - new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89,} - }; + { + new GradeEntry { Date = DateTime.Now, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89, } + }; var scoreSort = Builders.Sort.Descending(g => g.Score); @@ -252,10 +253,10 @@ public static UpdateResult UpdateManyPull() // Add duplicate values to Grades array var newGrades = new List - { - new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, - new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,} - }; + { + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95, } + }; var addUpdate = Builders.Update .PushEach("Grades", newGrades); _restaurantsCollection.UpdateMany(filter, addUpdate); @@ -278,10 +279,10 @@ public static async Task UpdateManyPullAsync() // Add duplicate values to Grades array var newGrades = new List - { - new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, - new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,} - }; + { + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95, } + }; var addUpdate = Builders.Update .PushEach("Grades", newGrades); await _restaurantsCollection.UpdateManyAsync(filter, addUpdate); @@ -304,12 +305,12 @@ public static UpdateResult UpdateManyPullAll() // Add duplicate values to Grades array var newGrades = new List - { - new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, - new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,}, - new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85 }, - new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85,} - }; + { + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95, }, + new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85, } + }; var addUpdate = Builders.Update .PushEach("Grades", newGrades); _restaurantsCollection.UpdateMany(filter, addUpdate); @@ -333,12 +334,12 @@ public static async Task UpdateManyPullAllAsync() // Add duplicate values to Grades array var newGrades = new List - { - new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, - new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,}, - new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85 }, - new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85,} - }; + { + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95, }, + new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85 }, + new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85, } + }; var addUpdate = Builders.Update .PushEach("Grades", newGrades); await _restaurantsCollection.UpdateManyAsync(filter, addUpdate); @@ -362,12 +363,12 @@ public static UpdateResult UpdateManyPullFilter() // Add GradeEntry values with "Grade = F" to Grades array var newGrades = new List - { - new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 10 }, - new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 21,}, - new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 47 }, - new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 6,} - }; + { + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 10 }, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 21, }, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 47 }, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 6, } + }; var addUpdate = Builders.Update .PushEach("Grades", newGrades); _restaurantsCollection.UpdateMany(filter, addUpdate); @@ -390,12 +391,12 @@ public static async Task UpdateManyPullFilterAsync() // Add GradeEntry values with "Grade = F" to Grades array var newGrades = new List - { - new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 10 }, - new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 21,}, - new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 47 }, - new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 6,} - }; + { + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 10 }, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 21, }, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 47 }, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 6, } + }; var addUpdate = Builders.Update .PushEach("Grades", newGrades); await _restaurantsCollection.UpdateManyAsync(filter, addUpdate); @@ -414,7 +415,7 @@ public static UpdateResult UpdateManyPositional() { // start-update-many-positional var filter = Builders.Filter - .Eq("name", "Downtown Deli") & + .Eq("name", "Downtown Deli") & Builders.Filter.Eq("grades.grade", "A"); // Set Score = 100 in first GradeEntry where Grade = "A" @@ -427,11 +428,26 @@ public static UpdateResult UpdateManyPositional() // end-update-many-positional } + public static UpdateResult UpdateManyPositionalLinq() + { + // start-update-many-positional-linq + var filter = Builders.Filter + .Eq("name", "Downtown Deli") & + Builders.Filter.Eq("grades.grade", "A"); + + var update = Builders.Update + .Set(restaurant => restaurant.Grades.FirstMatchingElement().Score, 100); + + var result = _restaurantsCollection.UpdateMany(filter, update); + return result; + // end-update-many-positional-linq + } + public static async Task UpdateManyPositionalAsync() { // start-update-many-positional-async var filter = Builders.Filter - .Eq("name", "Downtown Deli") & + .Eq("name", "Downtown Deli") & Builders.Filter .Eq("grades.grade", "A"); @@ -445,6 +461,22 @@ public static async Task UpdateManyPositionalAsync() // end-update-many-positional-async } + public static async Task UpdateManyPositionalLinqAsync() + { + // start-update-many-positional-linq-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli") & + Builders.Filter.Eq("grades.grade", "A"); + + var update = Builders.Update + .Set(restaurant => restaurant.Grades.FirstMatchingElement().Score, 100); + + var result = await _restaurantsCollection.UpdateManyAsync(filter, update); + + return result; + // end-update-many-positional-linq-async + } + public static UpdateResult UpdateManyAllPositional() { // start-update-many-allpositional @@ -461,6 +493,22 @@ public static UpdateResult UpdateManyAllPositional() // end-update-many-allpositional } + public static UpdateResult UpdateManyAllPositionalLinq() + { + // start-update-many-allpositional-linq + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Set Score = 100 in all GradeEntry objects + var update = Builders.Update + .Set(restaurant => restaurant.Grades.AllElements().Score, 100); + + var result = _restaurantsCollection.UpdateMany(filter, update); + + return result; + // end-update-many-allpositional-linq + } + public static async Task UpdateManyAllPositionalAsync() { // start-update-many-allpositional-async @@ -477,6 +525,22 @@ public static async Task UpdateManyAllPositionalAsync() // end-update-many-allpositional-async } + public static async Task UpdateManyAllPositionalLinqAsync() + { + // start-update-many-allpositional-linq-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Set Score = 100 in all GradeEntry objects + var update = Builders.Update + .Set(restaurant => restaurant.Grades.AllElements().Score, 100); + + var result = await _restaurantsCollection.UpdateManyAsync(filter, update); + + return result; + // end-update-many-allpositional-linq-async + } + public static UpdateResult UpdateManyFilteredPositional() { // start-update-many-filteredpositional @@ -484,13 +548,13 @@ public static UpdateResult UpdateManyFilteredPositional() .Eq("name", "Downtown Deli"); var arrayFilters = new List - { - new BsonDocumentArrayFilterDefinition( - new BsonDocument - { - { "gradeEntry.score", new BsonDocument { { "$gte", 94} } } - }) - }; + { + new BsonDocumentArrayFilterDefinition( + new BsonDocument + { + { "gradeEntry.score", new BsonDocument { { "$gte", 94 } } } + }) + }; // Set Grade = "A" in all GradeEntry objects where Score >= 94 var update = Builders.Update @@ -503,6 +567,31 @@ public static UpdateResult UpdateManyFilteredPositional() // end-update-many-filteredpositional } + public static UpdateResult UpdateManyFilteredPositionalLinq() + { + // start-update-many-filteredpositional-linq + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var arrayFilters = new List + { + new BsonDocumentArrayFilterDefinition( + new BsonDocument + { + { "gradeEntry.score", new BsonDocument { { "$gte", 94 } } } + }) + }; + + var update = Builders.Update + .Set(restaurant => restaurant.Grades.AllMatchingElements("gradeEntry").Score, 100); + + var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; + var result = _restaurantsCollection.UpdateMany(filter, update, updateOptions); + + return result; + // end-update-many-filteredpositional-linq + } + public static async Task UpdateManyFilteredPositionalAsync() { // start-update-many-filteredpositional-async @@ -510,23 +599,48 @@ public static async Task UpdateManyFilteredPositionalAsync() .Eq("name", "Downtown Deli"); var arrayFilters = new List - { - new BsonDocumentArrayFilterDefinition( - new BsonDocument - { - { "gradeEntry.score", new BsonDocument { { "$gte", 94} } } - }) - }; + { + new BsonDocumentArrayFilterDefinition( + new BsonDocument + { + { "gradeEntry.score", new BsonDocument { { "$gte", 94 } } } + }) + }; // Set Grade = "A" in all GradeEntry objects where Score >= 94 var update = Builders.Update .Set("grades.$[gradeEntry].grade", "F"); var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; - var result = await _restaurantsCollection.UpdateOneAsync(filter, update, updateOptions); + var result = await _restaurantsCollection.UpdateManyAsync(filter, update, updateOptions); return result; // end-update-many-filteredpositional-async } -} + + public static async Task UpdateManyFilteredPositionalLinqAsync() + { + // start-update-many-filteredpositional-linq-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var arrayFilters = new List + { + new BsonDocumentArrayFilterDefinition( + new BsonDocument + { + { "gradeEntry.score", new BsonDocument { { "$gte", 94 } } } + }) + }; + + // Set Grade = "A" in all GradeEntry objects where Score >= 94 + var update = Builders.Update + .Set(restaurant => restaurant.Grades.AllMatchingElements("gradeEntry").Score, 100); + + var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; + var result = await _restaurantsCollection.UpdateManyAsync(filter, update, updateOptions); + + return result; + // end-update-many-filteredpositional-linq-async + } } \ No newline at end of file diff --git a/source/includes/code-examples/update-one/UpdateOneArrays.cs b/source/includes/code-examples/update-one/UpdateOneArrays.cs index 463c60ef..a34b31f2 100644 --- a/source/includes/code-examples/update-one/UpdateOneArrays.cs +++ b/source/includes/code-examples/update-one/UpdateOneArrays.cs @@ -1,6 +1,7 @@ using MongoDB.Bson; using MongoDB.Bson.Serialization.Conventions; using MongoDB.Driver; +using MongoDB.Driver.Linq; using WriteData.Models; namespace CSharpExamples.WriteData; @@ -427,6 +428,21 @@ public static UpdateResult UpdateOnePositional() // end-update-one-positional } + public static UpdateResult UpdateOnePositionalLinq() + { + // start-update-one-positional-linq + var filter = Builders.Filter + .Eq("name", "Downtown Deli") & + Builders.Filter.Eq("grades.grade", "A"); + + var update = Builders.Update + .Set(restaurant => restaurant.Grades.FirstMatchingElement().Score, 100); + + var result = _restaurantsCollection.UpdateOne(filter, update); + return result; + // end-update-one-positional-linq + } + public static async Task UpdateOnePositionalAsync() { // start-update-one-positional-async @@ -445,6 +461,22 @@ public static async Task UpdateOnePositionalAsync() // end-update-one-positional-async } + public static async Task UpdateOnePositionalLinqAsync() + { + // start-update-one-positional-linq-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli") & + Builders.Filter.Eq("grades.grade", "A"); + + var update = Builders.Update + .Set(restaurant => restaurant.Grades.FirstMatchingElement().Score, 100); + + var result = await _restaurantsCollection.UpdateOneAsync(filter, update); + + return result; + // end-update-one-positional-linq-async + } + public static UpdateResult UpdateOneAllPositional() { // start-update-one-allpositional @@ -461,6 +493,22 @@ public static UpdateResult UpdateOneAllPositional() // end-update-one-allpositional } + public static UpdateResult UpdateOneAllPositionalLinq() + { + // start-update-one-allpositional-linq + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Set Score = 100 in all GradeEntry objects + var update = Builders.Update + .Set(restaurant => restaurant.Grades.AllElements().Score, 100); + + var result = _restaurantsCollection.UpdateOne(filter, update); + + return result; + // end-update-one-allpositional-linq + } + public static async Task UpdateOneAllPositionalAsync() { // start-update-one-allpositional-async @@ -477,6 +525,22 @@ public static async Task UpdateOneAllPositionalAsync() // end-update-one-allpositional-async } + public static async Task UpdateOneAllPositionalLinqAsync() + { + // start-update-one-allpositional-linq-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + // Set Score = 100 in all GradeEntry objects + var update = Builders.Update + .Set(restaurant => restaurant.Grades.AllElements().Score, 100); + + var result = await _restaurantsCollection.UpdateOneAsync(filter, update); + + return result; + // end-update-one-allpositional-linq-async + } + public static UpdateResult UpdateOneFilteredPositional() { // start-update-one-filteredpositional @@ -503,6 +567,31 @@ public static UpdateResult UpdateOneFilteredPositional() // end-update-one-filteredpositional } + public static UpdateResult UpdateOneFilteredPositionalLinq() + { + // start-update-one-filteredpositional-linq + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var arrayFilters = new List + { + new BsonDocumentArrayFilterDefinition( + new BsonDocument + { + { "gradeEntry.score", new BsonDocument { { "$gte", 94} } } + }) + }; + + var update = Builders.Update + .Set(restaurant => restaurant.Grades.AllMatchingElements("gradeEntry").Score, 100); + + var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; + var result = _restaurantsCollection.UpdateOne(filter, update, updateOptions); + + return result; + // end-update-one-filteredpositional-linq + } + public static async Task UpdateOneFilteredPositionalAsync() { // start-update-one-filteredpositional-async @@ -528,4 +617,30 @@ public static async Task UpdateOneFilteredPositionalAsync() return result; // end-update-one-filteredpositional-async } + + public static async Task UpdateOneFilteredPositionalLinqAsync() + { + // start-update-one-filteredpositional-linq-async + var filter = Builders.Filter + .Eq("name", "Downtown Deli"); + + var arrayFilters = new List + { + new BsonDocumentArrayFilterDefinition( + new BsonDocument + { + { "gradeEntry.score", new BsonDocument { { "$gte", 94} } } + }) + }; + + // Set Grade = "A" in all GradeEntry objects where Score >= 94 + var update = Builders.Update + .Set(restaurant => restaurant.Grades.AllMatchingElements("gradeEntry").Score, 100); + + var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; + var result = await _restaurantsCollection.UpdateOneAsync(filter, update, updateOptions); + + return result; + // end-update-one-filteredpositional-linq-async + } } \ No newline at end of file diff --git a/source/includes/page-templates/update/arrays.rst b/source/includes/page-templates/update/arrays.rst index 6bb454a9..1681bcbf 100644 --- a/source/includes/page-templates/update/arrays.rst +++ b/source/includes/page-templates/update/arrays.rst @@ -11,8 +11,8 @@ To create an ``UpdateDefinition`` object for one of these operators, call the co method from the ``Builders.Update`` property. The following sections describe these methods in more detail. -After you create an ``UpdateDefinition`` object, pass it to the ``|sync-method|()`` -or ``|sync-method|Async()`` method. For more information about these methods, see +After you create an ``UpdateDefinition`` object, pass it to the |sync-method| +or |async-method| method. For more information about these methods, see the |update-page-link| page. .. include:: /includes/method-overloads.rst @@ -305,7 +305,10 @@ This method accepts the following parameters: You can use the :manual:`positional operator ` in combination with the ``Set()`` method to query and update specific values in the array. -The following sections describe different ways to use the positional operator. +If you're using the LINQ3 provider, the {+driver-short+} also supports LINQ syntax in +place of the positional operator. + +The following sections describe different ways to update matching values in an array field. First Matching Value ~~~~~~~~~~~~~~~~~~~~ diff --git a/source/includes/page-templates/update/update.rst b/source/includes/page-templates/update/update.rst index 99bfc6ee..c04bdc3e 100644 --- a/source/includes/page-templates/update/update.rst +++ b/source/includes/page-templates/update/update.rst @@ -6,8 +6,8 @@ values in MongoDB documents. The {+driver-short+} provides the following methods to update values: -- ``|sync-method|()``: Updates one or more fields in |single-or-multiple|. -- ``|async-method|()``: The asynchronous version of ``|sync-method|()``. +- |sync-method|: Updates one or more fields in |single-or-multiple|. +- |async-method|: The asynchronous version of |sync-method|()``. The following sections describe these methods in more detail. @@ -21,7 +21,7 @@ The following sections describe these methods in more detail. Methods and Parameters ---------------------- -The ``|sync-method|()`` and ``|async-method|()`` methods accept the following parameters: +The |sync-method| and |async-method| methods accept the following parameters: .. list-table:: :widths: 30 70 @@ -60,7 +60,7 @@ The ``|sync-method|()`` and ``|async-method|()`` methods accept the following pa Update Multiple Values ---------------------- -The ``|sync-method|()`` and ``|async-method|()`` methods each accept only one +The |sync-method| and |async-method| methods each accept only one ``UpdateDefinition`` object. The following sections describe how to update multiple values in a single method call. @@ -139,7 +139,7 @@ operation: Configuration Options --------------------- -The ``|sync-method|()`` and ``|async-method|()`` methods optionally accept an +The |sync-method| and |async-method| methods optionally accept an ``UpdateOptions`` object as a parameter. You can use this argument to configure the update operation. @@ -206,7 +206,7 @@ The ``UpdateOptions`` class contains the following properties: Return Value ------------ -The ``|sync-method|()`` returns an ``UpdateResult``, and the ``|async-method|()`` +The |sync-method| returns an ``UpdateResult``, and the |async-method| method returns an asynchronous version of this type, a ``Task`` object. The ``UpdateResult`` class contains the following properties: From 33cae16b5f0d27088e156d252c5dc3cd1d74f727 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Tue, 26 Nov 2024 11:42:35 -0600 Subject: [PATCH 24/39] first draft --- source/fundamentals/crud/write-operations.txt | 4 +- .../update-many/UpdateManyArrays.cs | 40 ++++++++-------- .../includes/page-templates/update/arrays.rst | 48 ------------------- 3 files changed, 22 insertions(+), 70 deletions(-) diff --git a/source/fundamentals/crud/write-operations.txt b/source/fundamentals/crud/write-operations.txt index 5ca9a5c1..bb946729 100644 --- a/source/fundamentals/crud/write-operations.txt +++ b/source/fundamentals/crud/write-operations.txt @@ -11,8 +11,8 @@ Write Operations :caption: Write Operations Insert - Update - Update + Update One + Update Many Replace Delete Bulk Write Operations diff --git a/source/includes/code-examples/update-many/UpdateManyArrays.cs b/source/includes/code-examples/update-many/UpdateManyArrays.cs index 5f6c98f8..8c446a95 100644 --- a/source/includes/code-examples/update-many/UpdateManyArrays.cs +++ b/source/includes/code-examples/update-many/UpdateManyArrays.cs @@ -106,7 +106,7 @@ public static UpdateResult UpdateManyPushEach() var newGrades = new List { new GradeEntry { Date = DateTime.Now, Grade = "A", Score = 95 }, - new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89, } + new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89,} }; var scoreSort = Builders.Sort.Descending(g => g.Score); @@ -132,7 +132,7 @@ public static async Task UpdateManyPushEachAsync() var newGrades = new List { new GradeEntry { Date = DateTime.Now, Grade = "A", Score = 95 }, - new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89, } + new GradeEntry { Date = DateTime.Now, Grade = "B+", Score = 89,} }; var scoreSort = Builders.Sort.Descending(g => g.Score); @@ -255,7 +255,7 @@ public static UpdateResult UpdateManyPull() var newGrades = new List { new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, - new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95, } + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,} }; var addUpdate = Builders.Update .PushEach("Grades", newGrades); @@ -281,7 +281,7 @@ public static async Task UpdateManyPullAsync() var newGrades = new List { new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, - new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95, } + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,} }; var addUpdate = Builders.Update .PushEach("Grades", newGrades); @@ -307,9 +307,9 @@ public static UpdateResult UpdateManyPullAll() var newGrades = new List { new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, - new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95, }, + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,}, new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85 }, - new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85, } + new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85,} }; var addUpdate = Builders.Update .PushEach("Grades", newGrades); @@ -336,9 +336,9 @@ public static async Task UpdateManyPullAllAsync() var newGrades = new List { new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95 }, - new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95, }, + new GradeEntry { Date = DateTime.MinValue, Grade = "A", Score = 95,}, new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85 }, - new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85, } + new GradeEntry { Date = DateTime.MinValue, Grade = "B", Score = 85,} }; var addUpdate = Builders.Update .PushEach("Grades", newGrades); @@ -365,9 +365,9 @@ public static UpdateResult UpdateManyPullFilter() var newGrades = new List { new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 10 }, - new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 21, }, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 21,}, new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 47 }, - new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 6, } + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 6,} }; var addUpdate = Builders.Update .PushEach("Grades", newGrades); @@ -393,9 +393,9 @@ public static async Task UpdateManyPullFilterAsync() var newGrades = new List { new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 10 }, - new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 21, }, + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 21,}, new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 47 }, - new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 6, } + new GradeEntry { Date = DateTime.Now, Grade = "F", Score = 6,} }; var addUpdate = Builders.Update .PushEach("Grades", newGrades); @@ -415,7 +415,7 @@ public static UpdateResult UpdateManyPositional() { // start-update-many-positional var filter = Builders.Filter - .Eq("name", "Downtown Deli") & + .Eq("name", "Downtown Deli") & Builders.Filter.Eq("grades.grade", "A"); // Set Score = 100 in first GradeEntry where Grade = "A" @@ -432,7 +432,7 @@ public static UpdateResult UpdateManyPositionalLinq() { // start-update-many-positional-linq var filter = Builders.Filter - .Eq("name", "Downtown Deli") & + .Eq("name", "Downtown Deli") & Builders.Filter.Eq("grades.grade", "A"); var update = Builders.Update @@ -447,7 +447,7 @@ public static async Task UpdateManyPositionalAsync() { // start-update-many-positional-async var filter = Builders.Filter - .Eq("name", "Downtown Deli") & + .Eq("name", "Downtown Deli") & Builders.Filter .Eq("grades.grade", "A"); @@ -465,7 +465,7 @@ public static async Task UpdateManyPositionalLinqAsync() { // start-update-many-positional-linq-async var filter = Builders.Filter - .Eq("name", "Downtown Deli") & + .Eq("name", "Downtown Deli") & Builders.Filter.Eq("grades.grade", "A"); var update = Builders.Update @@ -552,7 +552,7 @@ public static UpdateResult UpdateManyFilteredPositional() new BsonDocumentArrayFilterDefinition( new BsonDocument { - { "gradeEntry.score", new BsonDocument { { "$gte", 94 } } } + { "gradeEntry.score", new BsonDocument { { "$gte", 94} } } }) }; @@ -578,7 +578,7 @@ public static UpdateResult UpdateManyFilteredPositionalLinq() new BsonDocumentArrayFilterDefinition( new BsonDocument { - { "gradeEntry.score", new BsonDocument { { "$gte", 94 } } } + { "gradeEntry.score", new BsonDocument { { "$gte", 94} } } }) }; @@ -603,7 +603,7 @@ public static async Task UpdateManyFilteredPositionalAsync() new BsonDocumentArrayFilterDefinition( new BsonDocument { - { "gradeEntry.score", new BsonDocument { { "$gte", 94 } } } + { "gradeEntry.score", new BsonDocument { { "$gte", 94} } } }) }; @@ -629,7 +629,7 @@ public static async Task UpdateManyFilteredPositionalLinqAsync() new BsonDocumentArrayFilterDefinition( new BsonDocument { - { "gradeEntry.score", new BsonDocument { { "$gte", 94 } } } + { "gradeEntry.score", new BsonDocument { { "$gte", 94} } } }) }; diff --git a/source/includes/page-templates/update/arrays.rst b/source/includes/page-templates/update/arrays.rst index 1681bcbf..44a3145b 100644 --- a/source/includes/page-templates/update/arrays.rst +++ b/source/includes/page-templates/update/arrays.rst @@ -352,54 +352,6 @@ to 100 in |matching-document-or-documents|: |allpositional-code-example-tabs| -LINQ3 Provider -~~~~~~~~~~~~~~ - -LINQ syntax contains a positional operator (``$``) that you can use to update elements in an array field. -Previous versions of the {+driver-short+} supported both the LINQ2 and LINQ3 providers. -In LINQ2, you could use ``-1`` to indicate use of the positional operator. - -For example, the ``Restaurant`` class contains an array field named ``Grades`` that -contains multiple ``GradeEntry`` elements. If your application were using the LINQ2 -provider, you could use the following code sample to update the -``Grade`` field of the first element in this array: - -.. code-block:: csharp - :linenos: - - var anArrayId = ObjectId.GenerateNewId(); - var another = new Restaurant - { - Id = ObjectId.GenerateNewId(), - AnArrayMember = new List - { - new AnArrayClass { Id = anArrayId, Deleted = false } - } - }; - - await collection.UpdateOneAsync( - r => r.Id == "targetId" && r.AnArrayMember.Any(l => l.Id == anArrayId), - Builders.Update.Set(l => l.AnArrayMember.ElementAt(-1).Deleted, true)); - -.. code-block:: csharp - :linenos: - - var anArrayId = ObjectId.GenerateNewId(); - var another = new Restaurant - { - Id = ObjectId.GenerateNewId(), - AnArrayMember = new List - { - new AnArrayClass { Id = anArrayId, Deleted = false } - } - }; - - await collection.UpdateOneAsync( - r => r.Id == "targetId" && r.AnArrayMember.Any(l => l.Id == anArrayId), - Builders.Update.Set(l => l.AnArrayMember.ElementAt(-1).Deleted, true)); - -This no longer works in LINQ3. Instead, you must use the following syntax: - API Documentation ----------------- From 4f7bbe9cbfc34b6ab67a64ab5a7f298e42a7bc93 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Tue, 26 Nov 2024 12:04:52 -0600 Subject: [PATCH 25/39] fixes --- .../crud/write-operations/bulk-write.txt | 3 ++- .../crud/write-operations/replace.txt | 6 +++--- .../crud/write-operations/update-many.txt | 11 +++++++---- .../crud/write-operations/update-one.txt | 11 +++++++---- .../code-examples/replace-one/ReplaceOne.cs | 4 ++-- .../includes/page-templates/update/update.rst | 7 +++---- source/quick-reference.txt | 19 ++++++++++--------- source/usage-examples/updateMany.txt | 2 +- source/usage-examples/updateOne.txt | 2 +- 9 files changed, 36 insertions(+), 29 deletions(-) diff --git a/source/fundamentals/crud/write-operations/bulk-write.txt b/source/fundamentals/crud/write-operations/bulk-write.txt index 8da9b794..37346e76 100644 --- a/source/fundamentals/crud/write-operations/bulk-write.txt +++ b/source/fundamentals/crud/write-operations/bulk-write.txt @@ -559,7 +559,8 @@ Additional Information To learn how to perform individual write operations, see the following guides: -- :ref:`csharp-change-guide` +- :ref:`csharp-update-one` +- :ref:`csharp-update-many` - :ref:`csharp-insert-guide` - :ref:`csharp-delete-guide` diff --git a/source/fundamentals/crud/write-operations/replace.txt b/source/fundamentals/crud/write-operations/replace.txt index d8bf2c14..b9f1d353 100644 --- a/source/fundamentals/crud/write-operations/replace.txt +++ b/source/fundamentals/crud/write-operations/replace.txt @@ -77,7 +77,7 @@ method. These methods accept the following parameters: query filters, see the :manual:`{+mdb-server+} manual `. - **Data Type:** `FilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ + **Data Type:** `FilterDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ * - ``replacement`` - A *replacement* document, which specifies the fields and values to insert in the new @@ -90,7 +90,7 @@ method. These methods accept the following parameters: - *Optional.* An instance of the ``ReplaceOptions`` class that specifies the configuration for the replace operation. The default value is ``null``. - **Data Type:** `ReplaceOptions <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.ReplaceOptions.html>`__ + **Data Type:** `ReplaceOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ReplaceOptions.html>`__ * - ``cancellationToken`` - *Optional.* A token that you can use to cancel the operation. @@ -265,7 +265,7 @@ The ``ReplaceOneResult`` class contains the following properties: - The ID of the document that was upserted in the database, if the driver performed an upsert. - **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ + **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ API Documentation ~~~~~~~~~~~~~~~~~ diff --git a/source/fundamentals/crud/write-operations/update-many.txt b/source/fundamentals/crud/write-operations/update-many.txt index 258d22e8..772b058d 100644 --- a/source/fundamentals/crud/write-operations/update-many.txt +++ b/source/fundamentals/crud/write-operations/update-many.txt @@ -1,4 +1,3 @@ -.. _csharp-change-guide: .. _csharp-update-many: =========== @@ -38,10 +37,14 @@ Update Many documents - .. replacement:: tab-id + .. replacement:: fields-link + + :ref:`csharp-update-many-fields` + + .. replacement:: arrays-link + + :ref:`csharp-update-many-arrays` - update-many - .. replacement:: single-or-multiple multiple documents diff --git a/source/fundamentals/crud/write-operations/update-one.txt b/source/fundamentals/crud/write-operations/update-one.txt index ed3594db..29035369 100644 --- a/source/fundamentals/crud/write-operations/update-one.txt +++ b/source/fundamentals/crud/write-operations/update-one.txt @@ -1,4 +1,3 @@ -.. _csharp-change-guide: .. _csharp-update-one: ========== @@ -38,10 +37,14 @@ Update One document - .. replacement:: tab-id + .. replacement:: fields-link - update-one - + :ref:`csharp-update-one-fields` + + .. replacement:: arrays-link + + :ref:`csharp-update-one-arrays` + .. replacement:: single-or-multiple a single document diff --git a/source/includes/code-examples/replace-one/ReplaceOne.cs b/source/includes/code-examples/replace-one/ReplaceOne.cs index 0efe398c..4f37ae43 100644 --- a/source/includes/code-examples/replace-one/ReplaceOne.cs +++ b/source/includes/code-examples/replace-one/ReplaceOne.cs @@ -47,7 +47,7 @@ public static void Main(string[] args) private static ReplaceOneResult ReplaceOneRestaurant() { - // start-replace-one-sync + // start-replace-one // Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza" var filter = Builders.Filter .Eq(r => r.Cuisine, "Pizza"); @@ -67,7 +67,7 @@ private static ReplaceOneResult ReplaceOneRestaurant() // Replaces the existing restaurant document with the new document return _restaurantsCollection.ReplaceOne(filter, newPizzaRestaurant); - // end-replace-one-sync + // end-replace-one } private static ReplaceOneResult ReplaceOneRestaurantWithOptions() diff --git a/source/includes/page-templates/update/update.rst b/source/includes/page-templates/update/update.rst index c04bdc3e..54afc30b 100644 --- a/source/includes/page-templates/update/update.rst +++ b/source/includes/page-templates/update/update.rst @@ -7,7 +7,7 @@ values in MongoDB documents. The {+driver-short+} provides the following methods to update values: - |sync-method|: Updates one or more fields in |single-or-multiple|. -- |async-method|: The asynchronous version of |sync-method|()``. +- |async-method|: The asynchronous version of |sync-method|. The following sections describe these methods in more detail. @@ -35,13 +35,12 @@ The |sync-method| and |async-method| methods accept the following parameters: to update. To learn how to create a query filter, see :ref:`csharp-specify-query`. - **Data Type:** `FilterDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>` + **Data Type:** `FilterDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ * - ``update`` - An instance of the ``UpdateDefinition`` class. This object specifies the kind of update operation, the fields to update, and the new value for each field. To learn how to - create an ``UpdateDefinition`` object, - see :ref:`csharp-|tab-id|-fields` and :ref:`csharp-|tab-id|-arrays`. + create an ``UpdateDefinition`` object, see |fields-link| and |arrays-link|. **Data Type:** `UpdateDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinition-1.html>`__ diff --git a/source/quick-reference.txt b/source/quick-reference.txt index 6c85abc9..dc82f454 100644 --- a/source/quick-reference.txt +++ b/source/quick-reference.txt @@ -180,8 +180,8 @@ their related reference and API documentation. * - | **Update a Document** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateOne.html>`__ - | :ref:`Usage Example ` - | :ref:`Fundamentals ` + | :ref:`Usage Example ` + | :ref:`Fundamentals ` - .. code-block:: csharp :copyable: true @@ -197,8 +197,8 @@ their related reference and API documentation. * - | **Update a Document (Async)** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateOneAsync.html>`__ - | :ref:`Usage Example ` - | :ref:`Fundamentals ` + | :ref:`Usage Example ` + | :ref:`Fundamentals ` - .. code-block:: csharp :copyable: true @@ -214,8 +214,8 @@ their related reference and API documentation. * - | **Update Multiple Documents** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateMany.html>`__ - | :ref:`Usage Example ` - | :ref:`Fundamentals ` + | :ref:`Usage Example ` + | :ref:`Fundamentals ` - .. code-block:: csharp :copyable: true @@ -231,8 +231,8 @@ their related reference and API documentation. * - | **Update Multiple Documents (Async)** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateManyAsync.html>`__ - | :ref:`Usage Example ` - | :ref:`Fundamentals ` + | :ref:`Usage Example ` + | :ref:`Fundamentals ` - .. code-block:: csharp :copyable: true @@ -248,7 +248,8 @@ their related reference and API documentation. * - | **Update an Array in a Document** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateOne.html>`__ - | :ref:`Fundamentals ` + | :ref:`Fundamentals (Update One) ` + | :ref:`Fundamentals (Update Many) ` - .. code-block:: csharp :copyable: true diff --git a/source/usage-examples/updateMany.txt b/source/usage-examples/updateMany.txt index 5d9b227b..7c1b5203 100644 --- a/source/usage-examples/updateMany.txt +++ b/source/usage-examples/updateMany.txt @@ -73,7 +73,7 @@ Running either of the preceding full examples prints the following results: More Information ---------------- -To learn more about updating documents, see the :ref:`csharp-change-guide` guide. +To learn more about updating documents, see the :ref:`csharp-update-many` guide. To learn more about using builders, see :ref:`csharp-builders`. diff --git a/source/usage-examples/updateOne.txt b/source/usage-examples/updateOne.txt index 9dc8207c..df6c799a 100644 --- a/source/usage-examples/updateOne.txt +++ b/source/usage-examples/updateOne.txt @@ -86,7 +86,7 @@ writes the following to the console: More Information ---------------- -To learn more about updating documents, see the :ref:`csharp-change-guide` guide. +To learn more about updating documents, see the :ref:`csharp-update-one` guide. To learn more about using builders, see :ref:`csharp-builders`. From fca4f6a587db2f590158b3e89fec62158874d003 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Tue, 26 Nov 2024 12:09:25 -0600 Subject: [PATCH 26/39] fix --- source/fundamentals/crud/write-operations/replace.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/fundamentals/crud/write-operations/replace.txt b/source/fundamentals/crud/write-operations/replace.txt index b9f1d353..86a3602a 100644 --- a/source/fundamentals/crud/write-operations/replace.txt +++ b/source/fundamentals/crud/write-operations/replace.txt @@ -119,8 +119,8 @@ corresponding code. :language: csharp :copyable: true :dedent: - :start-after: // start-replace-one-sync - :end-before: // end-replace-one-sync + :start-after: // start-replace-one + :end-before: // end-replace-one .. tab:: Asynchronous :tabid: replace-one-async From 20a8f6c9a45760796d02ec7b08bc3656a07f70cf Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Tue, 26 Nov 2024 13:41:14 -0600 Subject: [PATCH 27/39] update + replace fixes --- .../crud/write-operations/replace.txt | 31 ++---------------- .../crud/write-operations/update-many.txt | 32 ++++++++++++++++++- .../crud/write-operations/update-one.txt | 24 +++++++++++--- .../includes/page-templates/update/update.rst | 28 ++++++---------- 4 files changed, 64 insertions(+), 51 deletions(-) diff --git a/source/fundamentals/crud/write-operations/replace.txt b/source/fundamentals/crud/write-operations/replace.txt index 86a3602a..0da09086 100644 --- a/source/fundamentals/crud/write-operations/replace.txt +++ b/source/fundamentals/crud/write-operations/replace.txt @@ -29,34 +29,9 @@ These methods remove all fields (except the ``_id`` field) from the first docume matches the search criteria, then insert the fields and values you specify into the document. -Sample Data -~~~~~~~~~~~ - -The examples in this guide use the ``restaurants`` collection -from the ``sample_restaurants`` database. The documents in this -collection use the following ``Restaurant``, ``Address``, and ``GradeEntry`` -classes as models: - -.. literalinclude:: /includes/code-examples/Restaurant.cs - :language: csharp - :copyable: - :dedent: - -.. literalinclude:: /includes/code-examples/Address.cs - :language: csharp - :copyable: - :dedent: - -.. literalinclude:: /includes/code-examples/GradeEntry.cs - :language: csharp - :copyable: - :dedent: - -.. include:: /includes/convention-pack-note.rst - -This collection is from the :atlas:`sample datasets ` provided -by Atlas. See the :ref:`` to learn how to create a free MongoDB cluster -and load this sample data. +.. include:: /includes/method-overloads.rst + +.. include:: /includes/atlas-sample-data.rst Replace One Document -------------------- diff --git a/source/fundamentals/crud/write-operations/update-many.txt b/source/fundamentals/crud/write-operations/update-many.txt index 772b058d..d251dfae 100644 --- a/source/fundamentals/crud/write-operations/update-many.txt +++ b/source/fundamentals/crud/write-operations/update-many.txt @@ -48,6 +48,34 @@ Update Many .. replacement:: single-or-multiple multiple documents + + .. replacement:: usage-examples-link + + :ref:`csharp-examples-update-many` + + .. replacement:: sync-api-link + + `UpdateMany() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateMany.html>`__ + + .. replacement:: async-api-link + + `UpdateManyAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateManyAsync.html>`__ + + .. replacement:: instruqt-lab-component + + .. instruqt:: /mongodb-docs/tracks/update-a-document---c-net-driver?token=em_69t_l-j0BC_en7Uy + :title: UpdateManyAsync() Lesson + :drawer: + + .. replacement:: instruqt-lab-instructions + + This page includes a short interactive lab that demonstrates how to + modify data by using the ``UpdateManyAsync()`` method. You can complete this + lab directly in your browser window without installing MongoDB or a code editor. + + To start the lab, click the :guilabel:`Open Interactive Tutorial` button at the + top of the page. To expand the lab to a full-screen format, click the + full-screen button (:guilabel:`â›¶`) in the top-right corner of the lab pane. .. replacement:: combine-code-example-tabs @@ -95,4 +123,6 @@ Update Many :copyable: true :dedent: :start-after: // start-pipeline-async - :end-before: // end-pipeline-async \ No newline at end of file + :end-before: // end-pipeline-async + + diff --git a/source/fundamentals/crud/write-operations/update-one.txt b/source/fundamentals/crud/write-operations/update-one.txt index 29035369..d0a1c428 100644 --- a/source/fundamentals/crud/write-operations/update-one.txt +++ b/source/fundamentals/crud/write-operations/update-one.txt @@ -48,12 +48,28 @@ Update One .. replacement:: single-or-multiple a single document + + .. replacement:: usage-examples-link + + :ref:`csharp-examples-update-one` + + .. replacement:: sync-api-link + + `UpdateOne() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateOne.html>`__ + + .. replacement:: async-api-link + + `UpdateOneAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateOneAsync.html>`__ + + .. replacement:: instruqt-lab-component + + .. replacement:: instruqt-lab-instructions .. replacement:: combine-code-example-tabs .. tabs:: - .. tab:: UpdateOne (Sync) + .. tab:: Synchronous :tabid: update-one-sync .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs @@ -63,7 +79,7 @@ Update One :start-after: // start-combine-sync :end-before: // end-combine-sync - .. tab:: UpdateOne (Async) + .. tab:: Asynchronous :tabid: update-one-async .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs @@ -77,7 +93,7 @@ Update One .. tabs:: - .. tab:: UpdateOne (Sync) + .. tab:: Synchronous :tabid: update-one-sync .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs @@ -87,7 +103,7 @@ Update One :start-after: // start-pipeline-sync :end-before: // end-pipeline-sync - .. tab:: UpdateOne (Async) + .. tab:: Asynchronous :tabid: update-one-async .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs diff --git a/source/includes/page-templates/update/update.rst b/source/includes/page-templates/update/update.rst index 54afc30b..f8794f88 100644 --- a/source/includes/page-templates/update/update.rst +++ b/source/includes/page-templates/update/update.rst @@ -2,7 +2,7 @@ Overview -------- In this guide, you can learn how to use the {+driver-long+} to update -values in MongoDB documents. +values in |single-or-multiple|. The {+driver-short+} provides the following methods to update values: @@ -11,12 +11,9 @@ The {+driver-short+} provides the following methods to update values: The following sections describe these methods in more detail. -.. note:: Method Overloads +.. include:: /includes/method-overloads.rst - Many of the methods in this guide have multiple overloads. The examples - in this guide use the simplest overload for demonstration purposes. For - more information about the available overloads, see the - `API documentation. <{+new-api-root+}/index.html>`__ +.. include:: /includes/atlas-sample-data.rst Methods and Parameters ---------------------- @@ -248,10 +245,9 @@ The ``UpdateResult`` class contains the following properties: Additional Information ---------------------- -For runnable examples of the update operations, see the following usage -examples: +|instruqt-lab-instructions| -- :ref:`csharp-update-one` +For runnable examples of the update operations, see the |usage-examples-link| page. To learn more about creating query filters, see the :ref:`csharp-specify-query` guide. @@ -261,13 +257,9 @@ API Documentation For more information about any of the methods or types discussed in this guide, see the following API documentation: -* `|sync-method|() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.|sync-method|.html>`__ -* `|async-method|() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.|async-method|.html>`__ -* `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ -* `UpdateResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateResult.html>`__ +- |sync-api-link| +- |async-api-link| +- `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ +- `UpdateResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateResult.html>`__ -.. _csharp-update-instruqt-lab: - -.. instruqt:: /mongodb-docs/tracks/update-a-document---c-net-driver?token=em_69t_l-j0BC_en7Uy - :title: UpdateManyAsync() Lesson - :drawer: \ No newline at end of file +|instruqt-lab-component| \ No newline at end of file From b66ca4bfb2ef6cb17d55f26e23f755ebb2153b93 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Tue, 26 Nov 2024 14:12:46 -0600 Subject: [PATCH 28/39] build edits --- .../write-operations/update-many/arrays.txt | 36 +++---- .../write-operations/update-one/arrays.txt | 36 +++---- .../update-many/UpdateManyArrays.cs | 102 +++++++----------- .../update-one/UpdateOneArrays.cs | 100 ++++++----------- source/includes/method-overloads.rst | 2 +- .../includes/page-templates/update/arrays.rst | 8 +- .../includes/page-templates/update/fields.rst | 20 ++-- 7 files changed, 123 insertions(+), 181 deletions(-) diff --git a/source/fundamentals/crud/write-operations/update-many/arrays.txt b/source/fundamentals/crud/write-operations/update-many/arrays.txt index 51b1d7c6..c4e80d71 100644 --- a/source/fundamentals/crud/write-operations/update-many/arrays.txt +++ b/source/fundamentals/crud/write-operations/update-many/arrays.txt @@ -39,7 +39,7 @@ Update Arrays .. tabs:: - .. tab:: UpdateMany (Sync) + .. tab:: Synchronous :tabid: update-many-push-sync .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -49,7 +49,7 @@ Update Arrays :start-after: // start-update-many-push :end-before: // end-update-many-push - .. tab:: UpdateMany (Async) + .. tab:: Asynchronous :tabid: update-many-push-async .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -63,7 +63,7 @@ Update Arrays .. tabs:: - .. tab:: UpdateMany (Sync) + .. tab:: Synchronous :tabid: update-many-addtoset-sync .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -73,7 +73,7 @@ Update Arrays :start-after: // start-update-many-addtoset :end-before: // end-update-many-addtoset - .. tab:: UpdateMany (Async) + .. tab:: Asynchronous :tabid: update-many-addtoset-async .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -87,7 +87,7 @@ Update Arrays .. tabs:: - .. tab:: UpdateMany (Sync) + .. tab:: Synchronous :tabid: update-many-pusheach-sync .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -97,7 +97,7 @@ Update Arrays :start-after: // start-update-many-pusheach :end-before: // end-update-many-pusheach - .. tab:: UpdateMany (Async) + .. tab:: Asynchronous :tabid: update-many-pusheach-async .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -111,7 +111,7 @@ Update Arrays .. tabs:: - .. tab:: UpdateMany (Sync) + .. tab:: Synchronous :tabid: update-many-addtoset-sync .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -121,7 +121,7 @@ Update Arrays :start-after: // start-update-many-addtoseteach :end-before: // end-update-many-addtoseteach - .. tab:: UpdateMany (Async) + .. tab:: Asynchronous :tabid: update-many-addtoset-async .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -135,7 +135,7 @@ Update Arrays .. tabs:: - .. tab:: UpdateMany (Sync) + .. tab:: Synchronous :tabid: update-many-popfirst-sync .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -145,7 +145,7 @@ Update Arrays :start-after: // start-update-many-popfirst :end-before: // end-update-many-popfirst - .. tab:: UpdateMany (Async) + .. tab:: Asynchronous :tabid: update-many-popfirst-async .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -159,7 +159,7 @@ Update Arrays .. tabs:: - .. tab:: UpdateMany (Sync) + .. tab:: Synchronous :tabid: update-many-poplast-sync .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -169,7 +169,7 @@ Update Arrays :start-after: // start-update-many-poplast :end-before: // end-update-many-poplast - .. tab:: UpdateMany (Async) + .. tab:: Asynchronous :tabid: update-many-poplast-async .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -183,7 +183,7 @@ Update Arrays .. tabs:: - .. tab:: UpdateMany (Sync) + .. tab:: Synchronous :tabid: update-many-pull-sync .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -193,7 +193,7 @@ Update Arrays :start-after: // start-update-many-pull :end-before: // end-update-many-pull - .. tab:: UpdateMany (Async) + .. tab:: Asynchronous :tabid: update-many-pull-async .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -207,7 +207,7 @@ Update Arrays .. tabs:: - .. tab:: UpdateMany (Sync) + .. tab:: Synchronous :tabid: update-many-pullall-sync .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -217,7 +217,7 @@ Update Arrays :start-after: // start-update-many-pullall :end-before: // end-update-many-pullall - .. tab:: UpdateMany (Async) + .. tab:: Asynchronous :tabid: update-many-pullall-async .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -231,7 +231,7 @@ Update Arrays .. tabs:: - .. tab:: UpdateMany (Sync) + .. tab:: Synchronous :tabid: update-many-pullfilter-sync .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs @@ -241,7 +241,7 @@ Update Arrays :start-after: // start-update-many-pullfilter :end-before: // end-update-many-pullfilter - .. tab:: UpdateMany (Async) + .. tab:: Asynchronous :tabid: update-many-pullfilter-async .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs diff --git a/source/fundamentals/crud/write-operations/update-one/arrays.txt b/source/fundamentals/crud/write-operations/update-one/arrays.txt index 90b0b028..e733ac44 100644 --- a/source/fundamentals/crud/write-operations/update-one/arrays.txt +++ b/source/fundamentals/crud/write-operations/update-one/arrays.txt @@ -39,7 +39,7 @@ Update Arrays .. tabs:: - .. tab:: UpdateOne (Sync) + .. tab:: Synchronous :tabid: update-one-push-sync .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -49,7 +49,7 @@ Update Arrays :start-after: // start-update-one-push :end-before: // end-update-one-push - .. tab:: UpdateOne (Async) + .. tab:: Asynchronous :tabid: update-one-push-async .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -63,7 +63,7 @@ Update Arrays .. tabs:: - .. tab:: UpdateOne (Sync) + .. tab:: Synchronous :tabid: update-one-addtoset-sync .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -73,7 +73,7 @@ Update Arrays :start-after: // start-update-one-addtoset :end-before: // end-update-one-addtoset - .. tab:: UpdateOne (Async) + .. tab:: Asynchronous :tabid: update-one-addtoset-async .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -87,7 +87,7 @@ Update Arrays .. tabs:: - .. tab:: UpdateOne (Sync) + .. tab:: Synchronous :tabid: update-one-pusheach-sync .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -97,7 +97,7 @@ Update Arrays :start-after: // start-update-one-pusheach :end-before: // end-update-one-pusheach - .. tab:: UpdateOne (Async) + .. tab:: Asynchronous :tabid: update-one-pusheach-async .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -111,7 +111,7 @@ Update Arrays .. tabs:: - .. tab:: UpdateOne (Sync) + .. tab:: Synchronous :tabid: update-one-addtoset-sync .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -121,7 +121,7 @@ Update Arrays :start-after: // start-update-one-addtoseteach :end-before: // end-update-one-addtoseteach - .. tab:: UpdateOne (Async) + .. tab:: Asynchronous :tabid: update-one-addtoset-async .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -135,7 +135,7 @@ Update Arrays .. tabs:: - .. tab:: UpdateOne (Sync) + .. tab:: Synchronous :tabid: update-one-popfirst-sync .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -145,7 +145,7 @@ Update Arrays :start-after: // start-update-one-popfirst :end-before: // end-update-one-popfirst - .. tab:: UpdateOne (Async) + .. tab:: Asynchronous :tabid: update-one-popfirst-async .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -159,7 +159,7 @@ Update Arrays .. tabs:: - .. tab:: UpdateOne (Sync) + .. tab:: Synchronous :tabid: update-one-poplast-sync .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -169,7 +169,7 @@ Update Arrays :start-after: // start-update-one-poplast :end-before: // end-update-one-poplast - .. tab:: UpdateOne (Async) + .. tab:: Asynchronous :tabid: update-one-poplast-async .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -183,7 +183,7 @@ Update Arrays .. tabs:: - .. tab:: UpdateOne (Sync) + .. tab:: Synchronous :tabid: update-one-pull-sync .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -193,7 +193,7 @@ Update Arrays :start-after: // start-update-one-pull :end-before: // end-update-one-pull - .. tab:: UpdateOne (Async) + .. tab:: Asynchronous :tabid: update-one-pull-async .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -207,7 +207,7 @@ Update Arrays .. tabs:: - .. tab:: UpdateOne (Sync) + .. tab:: Synchronous :tabid: update-one-pullall-sync .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -217,7 +217,7 @@ Update Arrays :start-after: // start-update-one-pullall :end-before: // end-update-one-pullall - .. tab:: UpdateOne (Async) + .. tab:: Asynchronous :tabid: update-one-pullall-async .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -231,7 +231,7 @@ Update Arrays .. tabs:: - .. tab:: UpdateOne (Sync) + .. tab:: Synchronous :tabid: update-one-pullfilter-sync .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs @@ -241,7 +241,7 @@ Update Arrays :start-after: // start-update-one-pullfilter :end-before: // end-update-one-pullfilter - .. tab:: UpdateOne (Async) + .. tab:: Asynchronous :tabid: update-one-pullfilter-async .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs diff --git a/source/includes/code-examples/update-many/UpdateManyArrays.cs b/source/includes/code-examples/update-many/UpdateManyArrays.cs index 8c446a95..7e757516 100644 --- a/source/includes/code-examples/update-many/UpdateManyArrays.cs +++ b/source/includes/code-examples/update-many/UpdateManyArrays.cs @@ -26,8 +26,7 @@ public static void Setup() public static UpdateResult UpdateManyPush() { // start-update-many-push - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var update = Builders.Update .Push(restaurant => restaurant.Grades, new GradeEntry() @@ -46,8 +45,7 @@ public static UpdateResult UpdateManyPush() public static async Task UpdateManyPushAsync() { // start-update-many-push-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var update = Builders.Update .Push(restaurant => restaurant.Grades, new GradeEntry() @@ -66,8 +64,7 @@ public static async Task UpdateManyPushAsync() public static UpdateResult UpdateManyAddToSet() { // start-update-many-addtoset - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var firstGradeEntry = _restaurantsCollection.Find(filter).FirstOrDefault().Grades[0]; @@ -83,8 +80,7 @@ public static UpdateResult UpdateManyAddToSet() public static async Task UpdateManyAddToSetAsync() { // start-update-many-addtoset-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var firstGradeEntry = _restaurantsCollection.Find(filter).FirstOrDefault().Grades[0]; @@ -100,8 +96,7 @@ public static async Task UpdateManyAddToSetAsync() public static UpdateResult UpdateManyPushEach() { // start-update-many-pusheach - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var newGrades = new List { @@ -126,8 +121,7 @@ public static UpdateResult UpdateManyPushEach() public static async Task UpdateManyPushEachAsync() { // start-update-many-pusheach-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var newGrades = new List { @@ -152,8 +146,7 @@ public static async Task UpdateManyPushEachAsync() public static UpdateResult UpdateManyAddToSetEach() { // start-update-many-addtoseteach - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var doc = _restaurantsCollection.Find(filter).FirstOrDefault(); var firstGradeEntries = new List { doc.Grades[0], doc.Grades[1] }; @@ -170,8 +163,7 @@ public static UpdateResult UpdateManyAddToSetEach() public static async Task UpdateManyAddToSetEachAsync() { // start-update-many-addtoseteach-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var doc = _restaurantsCollection.Find(filter).FirstOrDefault(); var firstGradeEntries = new List { doc.Grades[0], doc.Grades[1] }; @@ -188,8 +180,7 @@ public static async Task UpdateManyAddToSetEachAsync() public static UpdateResult UpdateManyPopFirst() { // start-update-many-popfirst - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var update = Builders.Update .PopFirst(restaurant => restaurant.Grades); @@ -203,8 +194,7 @@ public static UpdateResult UpdateManyPopFirst() public static async Task UpdateManyPopFirstAsync() { // start-update-many-popfirst-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var update = Builders.Update .PopFirst(restaurant => restaurant.Grades); @@ -218,8 +208,7 @@ public static async Task UpdateManyPopFirstAsync() public static UpdateResult UpdateManyPopLast() { // start-update-many-poplast - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var update = Builders.Update .PopLast(restaurant => restaurant.Grades); @@ -233,8 +222,7 @@ public static UpdateResult UpdateManyPopLast() public static async Task UpdateManyPopLastAsync() { // start-update-many-poplast-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var update = Builders.Update .PopLast(restaurant => restaurant.Grades); @@ -248,8 +236,7 @@ public static async Task UpdateManyPopLastAsync() public static UpdateResult UpdateManyPull() { // start-update-many-pull - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); // Add duplicate values to Grades array var newGrades = new List @@ -274,8 +261,7 @@ public static UpdateResult UpdateManyPull() public static async Task UpdateManyPullAsync() { // start-update-many-pull-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); // Add duplicate values to Grades array var newGrades = new List @@ -300,8 +286,7 @@ public static async Task UpdateManyPullAsync() public static UpdateResult UpdateManyPullAll() { // start-update-many-pullall - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); // Add duplicate values to Grades array var newGrades = new List @@ -329,8 +314,7 @@ public static UpdateResult UpdateManyPullAll() public static async Task UpdateManyPullAllAsync() { // start-update-many-pullall-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); // Add duplicate values to Grades array var newGrades = new List @@ -358,8 +342,7 @@ public static async Task UpdateManyPullAllAsync() public static UpdateResult UpdateManyPullFilter() { // start-update-many-pullfilter - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); // Add GradeEntry values with "Grade = F" to Grades array var newGrades = new List @@ -386,8 +369,7 @@ public static UpdateResult UpdateManyPullFilter() public static async Task UpdateManyPullFilterAsync() { // start-update-many-pullfilter-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); // Add GradeEntry values with "Grade = F" to Grades array var newGrades = new List @@ -414,9 +396,8 @@ public static async Task UpdateManyPullFilterAsync() public static UpdateResult UpdateManyPositional() { // start-update-many-positional - var filter = Builders.Filter - .Eq("name", "Downtown Deli") & - Builders.Filter.Eq("grades.grade", "A"); + var filter = Builders.Filter.Eq("name", "Downtown Deli") & + Builders.Filter.Eq("grades.grade", "A"); // Set Score = 100 in first GradeEntry where Grade = "A" var update = Builders.Update @@ -431,10 +412,10 @@ public static UpdateResult UpdateManyPositional() public static UpdateResult UpdateManyPositionalLinq() { // start-update-many-positional-linq - var filter = Builders.Filter - .Eq("name", "Downtown Deli") & - Builders.Filter.Eq("grades.grade", "A"); + var filter = Builders.Filter.Eq("name", "Downtown Deli") & + Builders.Filter.Eq("grades.grade", "A"); + // Set Score = 100 in first GradeEntry where Grade = "A" var update = Builders.Update .Set(restaurant => restaurant.Grades.FirstMatchingElement().Score, 100); @@ -446,10 +427,8 @@ public static UpdateResult UpdateManyPositionalLinq() public static async Task UpdateManyPositionalAsync() { // start-update-many-positional-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli") & - Builders.Filter - .Eq("grades.grade", "A"); + var filter = Builders.Filter.Eq("name", "Downtown Deli") & + Builders.Filter.Eq("grades.grade", "A"); // Set Score = 100 in first GradeEntry where Grade = "A" var update = Builders.Update @@ -464,10 +443,10 @@ public static async Task UpdateManyPositionalAsync() public static async Task UpdateManyPositionalLinqAsync() { // start-update-many-positional-linq-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli") & - Builders.Filter.Eq("grades.grade", "A"); + var filter = Builders.Filter.Eq("name", "Downtown Deli") & + Builders.Filter.Eq("grades.grade", "A"); + // Set Score = 100 in first GradeEntry where Grade = "A" var update = Builders.Update .Set(restaurant => restaurant.Grades.FirstMatchingElement().Score, 100); @@ -480,8 +459,7 @@ public static async Task UpdateManyPositionalLinqAsync() public static UpdateResult UpdateManyAllPositional() { // start-update-many-allpositional - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); // Set Score = 100 in all GradeEntry objects var update = Builders.Update @@ -496,8 +474,7 @@ public static UpdateResult UpdateManyAllPositional() public static UpdateResult UpdateManyAllPositionalLinq() { // start-update-many-allpositional-linq - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); // Set Score = 100 in all GradeEntry objects var update = Builders.Update @@ -512,8 +489,7 @@ public static UpdateResult UpdateManyAllPositionalLinq() public static async Task UpdateManyAllPositionalAsync() { // start-update-many-allpositional-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); // Set Score = 100 in all GradeEntry objects var update = Builders.Update @@ -528,8 +504,7 @@ public static async Task UpdateManyAllPositionalAsync() public static async Task UpdateManyAllPositionalLinqAsync() { // start-update-many-allpositional-linq-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); // Set Score = 100 in all GradeEntry objects var update = Builders.Update @@ -544,8 +519,7 @@ public static async Task UpdateManyAllPositionalLinqAsync() public static UpdateResult UpdateManyFilteredPositional() { // start-update-many-filteredpositional - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var arrayFilters = new List { @@ -570,8 +544,7 @@ public static UpdateResult UpdateManyFilteredPositional() public static UpdateResult UpdateManyFilteredPositionalLinq() { // start-update-many-filteredpositional-linq - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var arrayFilters = new List { @@ -582,6 +555,7 @@ public static UpdateResult UpdateManyFilteredPositionalLinq() }) }; + // Set Grade = "A" in all GradeEntry objects where Score >= 94 var update = Builders.Update .Set(restaurant => restaurant.Grades.AllMatchingElements("gradeEntry").Score, 100); @@ -595,8 +569,7 @@ public static UpdateResult UpdateManyFilteredPositionalLinq() public static async Task UpdateManyFilteredPositionalAsync() { // start-update-many-filteredpositional-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var arrayFilters = new List { @@ -621,8 +594,7 @@ public static async Task UpdateManyFilteredPositionalAsync() public static async Task UpdateManyFilteredPositionalLinqAsync() { // start-update-many-filteredpositional-linq-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var arrayFilters = new List { diff --git a/source/includes/code-examples/update-one/UpdateOneArrays.cs b/source/includes/code-examples/update-one/UpdateOneArrays.cs index a34b31f2..73a78a02 100644 --- a/source/includes/code-examples/update-one/UpdateOneArrays.cs +++ b/source/includes/code-examples/update-one/UpdateOneArrays.cs @@ -26,8 +26,7 @@ public static void Setup() public static UpdateResult UpdateOnePush() { // start-update-one-push - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var update = Builders.Update .Push(restaurant => restaurant.Grades, new GradeEntry() @@ -46,8 +45,7 @@ public static UpdateResult UpdateOnePush() public static async Task UpdateOnePushAsync() { // start-update-one-push-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var update = Builders.Update .Push(restaurant => restaurant.Grades, new GradeEntry() @@ -66,8 +64,7 @@ public static async Task UpdateOnePushAsync() public static UpdateResult UpdateOneAddToSet() { // start-update-one-addtoset - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var firstGradeEntry = _restaurantsCollection.Find(filter).FirstOrDefault().Grades[0]; @@ -83,8 +80,7 @@ public static UpdateResult UpdateOneAddToSet() public static async Task UpdateOneAddToSetAsync() { // start-update-one-addtoset-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var firstGradeEntry = _restaurantsCollection.Find(filter).FirstOrDefault().Grades[0]; @@ -100,8 +96,7 @@ public static async Task UpdateOneAddToSetAsync() public static UpdateResult UpdateOnePushEach() { // start-update-one-pusheach - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var newGrades = new List { @@ -126,8 +121,7 @@ public static UpdateResult UpdateOnePushEach() public static async Task UpdateOnePushEachAsync() { // start-update-one-pusheach-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var newGrades = new List { @@ -152,8 +146,7 @@ public static async Task UpdateOnePushEachAsync() public static UpdateResult UpdateOneAddToSetEach() { // start-update-one-addtoseteach - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var doc = _restaurantsCollection.Find(filter).FirstOrDefault(); var firstGradeEntries = new List { doc.Grades[0], doc.Grades[1] }; @@ -170,8 +163,7 @@ public static UpdateResult UpdateOneAddToSetEach() public static async Task UpdateOneAddToSetEachAsync() { // start-update-one-addtoseteach-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var doc = _restaurantsCollection.Find(filter).FirstOrDefault(); var firstGradeEntries = new List { doc.Grades[0], doc.Grades[1] }; @@ -188,8 +180,7 @@ public static async Task UpdateOneAddToSetEachAsync() public static UpdateResult UpdateOnePopFirst() { // start-update-one-popfirst - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var update = Builders.Update .PopFirst(restaurant => restaurant.Grades); @@ -203,8 +194,7 @@ public static UpdateResult UpdateOnePopFirst() public static async Task UpdateOnePopFirstAsync() { // start-update-one-popfirst-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var update = Builders.Update .PopFirst(restaurant => restaurant.Grades); @@ -218,8 +208,7 @@ public static async Task UpdateOnePopFirstAsync() public static UpdateResult UpdateOnePopLast() { // start-update-one-poplast - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var update = Builders.Update .PopLast(restaurant => restaurant.Grades); @@ -233,8 +222,7 @@ public static UpdateResult UpdateOnePopLast() public static async Task UpdateOnePopLastAsync() { // start-update-one-poplast-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var update = Builders.Update .PopLast(restaurant => restaurant.Grades); @@ -248,8 +236,7 @@ public static async Task UpdateOnePopLastAsync() public static UpdateResult UpdateOnePull() { // start-update-one-pull - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); // Add duplicate values to Grades array var newGrades = new List @@ -274,8 +261,7 @@ public static UpdateResult UpdateOnePull() public static async Task UpdateOnePullAsync() { // start-update-one-pull-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); // Add duplicate values to Grades array var newGrades = new List @@ -300,8 +286,7 @@ public static async Task UpdateOnePullAsync() public static UpdateResult UpdateOnePullAll() { // start-update-one-pullall - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); // Add duplicate values to Grades array var newGrades = new List @@ -329,8 +314,7 @@ public static UpdateResult UpdateOnePullAll() public static async Task UpdateOnePullAllAsync() { // start-update-one-pullall-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); // Add duplicate values to Grades array var newGrades = new List @@ -358,8 +342,7 @@ public static async Task UpdateOnePullAllAsync() public static UpdateResult UpdateOnePullFilter() { // start-update-one-pullfilter - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); // Add GradeEntry values with "Grade = F" to Grades array var newGrades = new List @@ -386,8 +369,7 @@ public static UpdateResult UpdateOnePullFilter() public static async Task UpdateOnePullFilterAsync() { // start-update-one-pullfilter-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); // Add GradeEntry values with "Grade = F" to Grades array var newGrades = new List @@ -414,9 +396,8 @@ public static async Task UpdateOnePullFilterAsync() public static UpdateResult UpdateOnePositional() { // start-update-one-positional - var filter = Builders.Filter - .Eq("name", "Downtown Deli") & - Builders.Filter.Eq("grades.grade", "A"); + var filter = Builders.Filter.Eq("name", "Downtown Deli") & + Builders.Filter.Eq("grades.grade", "A"); // Set Score = 100 in first GradeEntry where Grade = "A" var update = Builders.Update @@ -431,9 +412,8 @@ public static UpdateResult UpdateOnePositional() public static UpdateResult UpdateOnePositionalLinq() { // start-update-one-positional-linq - var filter = Builders.Filter - .Eq("name", "Downtown Deli") & - Builders.Filter.Eq("grades.grade", "A"); + var filter = Builders.Filter.Eq("name", "Downtown Deli") & + Builders.Filter.Eq("grades.grade", "A"); var update = Builders.Update .Set(restaurant => restaurant.Grades.FirstMatchingElement().Score, 100); @@ -446,10 +426,8 @@ public static UpdateResult UpdateOnePositionalLinq() public static async Task UpdateOnePositionalAsync() { // start-update-one-positional-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli") & - Builders.Filter - .Eq("grades.grade", "A"); + var filter = Builders.Filter.Eq("name", "Downtown Deli") & + Builders.Filter.Eq("grades.grade", "A"); // Set Score = 100 in first GradeEntry where Grade = "A" var update = Builders.Update @@ -464,9 +442,8 @@ public static async Task UpdateOnePositionalAsync() public static async Task UpdateOnePositionalLinqAsync() { // start-update-one-positional-linq-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli") & - Builders.Filter.Eq("grades.grade", "A"); + var filter = Builders.Filter.Eq("name", "Downtown Deli") & + Builders.Filter.Eq("grades.grade", "A"); var update = Builders.Update .Set(restaurant => restaurant.Grades.FirstMatchingElement().Score, 100); @@ -480,8 +457,7 @@ public static async Task UpdateOnePositionalLinqAsync() public static UpdateResult UpdateOneAllPositional() { // start-update-one-allpositional - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); // Set Score = 100 in all GradeEntry objects var update = Builders.Update @@ -496,8 +472,7 @@ public static UpdateResult UpdateOneAllPositional() public static UpdateResult UpdateOneAllPositionalLinq() { // start-update-one-allpositional-linq - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); // Set Score = 100 in all GradeEntry objects var update = Builders.Update @@ -512,8 +487,7 @@ public static UpdateResult UpdateOneAllPositionalLinq() public static async Task UpdateOneAllPositionalAsync() { // start-update-one-allpositional-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); // Set Score = 100 in all GradeEntry objects var update = Builders.Update @@ -528,8 +502,7 @@ public static async Task UpdateOneAllPositionalAsync() public static async Task UpdateOneAllPositionalLinqAsync() { // start-update-one-allpositional-linq-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); // Set Score = 100 in all GradeEntry objects var update = Builders.Update @@ -544,8 +517,7 @@ public static async Task UpdateOneAllPositionalLinqAsync() public static UpdateResult UpdateOneFilteredPositional() { // start-update-one-filteredpositional - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var arrayFilters = new List { @@ -570,8 +542,7 @@ public static UpdateResult UpdateOneFilteredPositional() public static UpdateResult UpdateOneFilteredPositionalLinq() { // start-update-one-filteredpositional-linq - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var arrayFilters = new List { @@ -582,6 +553,7 @@ public static UpdateResult UpdateOneFilteredPositionalLinq() }) }; + // Set Grade = "A" in all GradeEntry objects where Score >= 94 var update = Builders.Update .Set(restaurant => restaurant.Grades.AllMatchingElements("gradeEntry").Score, 100); @@ -595,8 +567,7 @@ public static UpdateResult UpdateOneFilteredPositionalLinq() public static async Task UpdateOneFilteredPositionalAsync() { // start-update-one-filteredpositional-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var arrayFilters = new List { @@ -621,8 +592,7 @@ public static async Task UpdateOneFilteredPositionalAsync() public static async Task UpdateOneFilteredPositionalLinqAsync() { // start-update-one-filteredpositional-linq-async - var filter = Builders.Filter - .Eq("name", "Downtown Deli"); + var filter = Builders.Filter.Eq("name", "Downtown Deli"); var arrayFilters = new List { diff --git a/source/includes/method-overloads.rst b/source/includes/method-overloads.rst index a8ef6132..48d11b14 100644 --- a/source/includes/method-overloads.rst +++ b/source/includes/method-overloads.rst @@ -1,6 +1,6 @@ .. note:: Method Overloads Many of the methods on this page have multiple overloads. The examples - in this guide show only one overload for each method. For + in this guide show only one definition of each method. For more information about the available overloads, see the `API documentation. <{+new-api-root+}/index.html>`__ \ No newline at end of file diff --git a/source/includes/page-templates/update/arrays.rst b/source/includes/page-templates/update/arrays.rst index 44a3145b..44bb266b 100644 --- a/source/includes/page-templates/update/arrays.rst +++ b/source/includes/page-templates/update/arrays.rst @@ -68,7 +68,7 @@ The ``AddToSet()`` method accepts the following parameters: - Description * - ``field`` - - An expression that specifies the array field to add to. + - An expression that specifies the array field to add a value to. **Data Type:** ``Expression>>`` @@ -97,7 +97,7 @@ This method accepts the following parameters: - Description * - ``field`` - - An expression that specifies the array field to add to. + - An expression that specifies the array field to add one or more values to. **Data Type:** ``Expression>>`` @@ -143,7 +143,7 @@ This method accepts the following parameters: - Description * - ``field`` - - An expression that specifies the array field to add to. + - An expression that specifies the array field to add one or more values to. **Data Type:** ``Expression>>`` @@ -336,7 +336,7 @@ positional operator (``$[]``) in combination with the ``Set()`` meth The following example uses the ``Set()`` method and the filtered positional operator to update the ``Score`` property of all matching -``GradeEntry`` objects in the Grades`` array to 100 in |matching-document-or-documents|: +``GradeEntry`` objects in the ``Grades`` array to 100 in |matching-document-or-documents|: |filteredpositional-code-example-tabs| diff --git a/source/includes/page-templates/update/fields.rst b/source/includes/page-templates/update/fields.rst index b1fb1f1a..256aa2f2 100644 --- a/source/includes/page-templates/update/fields.rst +++ b/source/includes/page-templates/update/fields.rst @@ -231,15 +231,15 @@ method accepts the following parameter: API Documentation ----------------- -For more information about any of the methods or types discussed in this +For more information about any of the methods discussed in this guide, see the following API documentation: -- `Builders.Update.Inc() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders.Update.Inc-2.html>`__ -- `Builders.Update.Mul() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders.Update.Mul-2.html>`__ -- `Builders.Update.Rename() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders.Update.Rename-2.html>`__ -- `Builders.Update.Set() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders.Update.Set-2.html>`__ -- `Builders.Update.Max() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders.Update.Max-2.html>`__ -- `Builders.Update.Min() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders.Update.Min-2.html>`__ -- `Builders.Update.SetOnInsert() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders.Update.SetOnInsert-2.html>`__ -- `Builders.Update.CurrentDate() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders.Update.CurrentDate-2.html>`__ -- `Builders.Update.Unset() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders.Update.Unset-2.html>`__ \ No newline at end of file +- `Builders.Update.Inc() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionBuilder-1.Inc.html>`__ +- `Builders.Update.Mul() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionBuilder-1.Mul.html>`__ +- `Builders.Update.Rename() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionBuilder-1.Rename.html>`__ +- `Builders.Update.Set() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionBuilder-1.Set.html>`__ +- `Builders.Update.Max() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionBuilder-1.Max.html>`__ +- `Builders.Update.Min() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionBuilder-1.Min.html>`__ +- `Builders.Update.SetOnInsert() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionBuilder-1.SetOnInsert.html>`__ +- `Builders.Update.CurrentDate() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionBuilder-1.CurrentDate.html>`__ +- `Builders.Update.Unset() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionBuilder-1.Unset.html>`__ \ No newline at end of file From f75288dacf7dd4282d5a3a9d7aca417c64ef4228 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Tue, 26 Nov 2024 14:20:01 -0600 Subject: [PATCH 29/39] fix --- source/includes/page-templates/update/arrays.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/includes/page-templates/update/arrays.rst b/source/includes/page-templates/update/arrays.rst index 44bb266b..2d4a8149 100644 --- a/source/includes/page-templates/update/arrays.rst +++ b/source/includes/page-templates/update/arrays.rst @@ -347,7 +347,7 @@ To update all values in an array that match a query filter, use the all-position (``$[]``) in combination with the ``Set()`` method. The following example uses the ``Set()`` method and the all-positional operator -to update the ``Score`` property of all ``GradeEntry`` objects in the Grades`` array +to update the ``Score`` property of all ``GradeEntry`` objects in the ``Grades`` array to 100 in |matching-document-or-documents|: |allpositional-code-example-tabs| From 011c4942b7db046c9090522356f3ae7c9bef466b Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Tue, 26 Nov 2024 14:24:46 -0600 Subject: [PATCH 30/39] fix --- source/includes/page-templates/update/fields.rst | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/source/includes/page-templates/update/fields.rst b/source/includes/page-templates/update/fields.rst index 256aa2f2..2c68c447 100644 --- a/source/includes/page-templates/update/fields.rst +++ b/source/includes/page-templates/update/fields.rst @@ -12,16 +12,6 @@ The {+driver-short+} supports the field update operators described in the update operation, call the corresponding method from the ``Builders.Update`` property. The following sections describe these methods in more detail. -.. tip:: Interactive Lab - - This page includes a short interactive lab that demonstrates how to - modify data by using the ``UpdateManyAsync()`` method. You can complete this - lab directly in your browser window without installing MongoDB or a code editor. - - To start the lab, click the :guilabel:`Open Interactive Tutorial` button at the - top of the page. To expand the lab to a full-screen format, click the - full-screen button (:guilabel:`â›¶`) in the top-right corner of the lab pane. - .. include:: /includes/method-overloads.rst .. include:: /includes/atlas-sample-data.rst From ebabbdc1f5c30256e80cc1f84f403e724e47cd8a Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Tue, 26 Nov 2024 14:42:26 -0600 Subject: [PATCH 31/39] breaking changes --- source/upgrade/v2.txt | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/source/upgrade/v2.txt b/source/upgrade/v2.txt index e999c685..6e134769 100644 --- a/source/upgrade/v2.txt +++ b/source/upgrade/v2.txt @@ -135,6 +135,11 @@ Version 2.19.0 Breaking Changes clientSettings.LinqProvider = LinqProvider.V2; var client = new MongoClient(clientSettings); + If your application uses the LINQ3 provider, you can't use ``-1`` to represent the + :manual:`positional operator ` + when updating an array. To learn how to use the positional operator, see + :ref:`` and :ref:``. + Version 2.14.0 Breaking Changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From ec2d51f99754b6761681e5b914d49c2e0822dacb Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Tue, 26 Nov 2024 14:46:03 -0600 Subject: [PATCH 32/39] fix --- source/upgrade/v2.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/source/upgrade/v2.txt b/source/upgrade/v2.txt index 6e134769..91c30e39 100644 --- a/source/upgrade/v2.txt +++ b/source/upgrade/v2.txt @@ -138,7 +138,8 @@ Version 2.19.0 Breaking Changes If your application uses the LINQ3 provider, you can't use ``-1`` to represent the :manual:`positional operator ` when updating an array. To learn how to use the positional operator, see - :ref:`` and :ref:``. + :ref:`Update One ` and + :ref:`Update Many `. Version 2.14.0 Breaking Changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From b8507369e6ed69c6bc35a31404b8c03744f80054 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Tue, 26 Nov 2024 14:54:14 -0600 Subject: [PATCH 33/39] vale --- source/fundamentals/crud/write-operations/replace.txt | 5 ++--- source/includes/page-templates/update/arrays.rst | 8 ++++---- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/source/fundamentals/crud/write-operations/replace.txt b/source/fundamentals/crud/write-operations/replace.txt index 0da09086..f7ef7512 100644 --- a/source/fundamentals/crud/write-operations/replace.txt +++ b/source/fundamentals/crud/write-operations/replace.txt @@ -116,9 +116,8 @@ Customize the Replace Operation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The ``ReplaceOne()`` and ``ReplaceOneAsync()`` methods optionally accept a -``ReplaceOptions`` object as an -additional parameter, which represents options you can use to configure the replace -operation. +``ReplaceOptions`` object as a parameter, which represents options you can use to +configure the replace operation. The ``ReplaceOptions`` class contains the following properties: diff --git a/source/includes/page-templates/update/arrays.rst b/source/includes/page-templates/update/arrays.rst index 2d4a8149..2dc535c8 100644 --- a/source/includes/page-templates/update/arrays.rst +++ b/source/includes/page-templates/update/arrays.rst @@ -304,7 +304,7 @@ This method accepts the following parameters: You can use the :manual:`positional operator ` -in combination with the ``Set()`` method to query and update specific values in the array. +with the ``Set()`` method to query and update specific values in the array. If you're using the LINQ3 provider, the {+driver-short+} also supports LINQ syntax in place of the positional operator. @@ -314,7 +314,7 @@ First Matching Value ~~~~~~~~~~~~~~~~~~~~ To update only the first value in an array that matches a query filter, use the -positional operator (``$``) in combination with the ``Set()`` method. +positional operator (``$``) with the ``Set()`` method. .. note:: @@ -332,7 +332,7 @@ All Matching Values ~~~~~~~~~~~~~~~~~~~ To update all values in an array that match a specified condition, use the filtered -positional operator (``$[]``) in combination with the ``Set()`` method. +positional operator (``$[]``) with the ``Set()`` method. The following example uses the ``Set()`` method and the filtered positional operator to update the ``Score`` property of all matching @@ -344,7 +344,7 @@ All Values ~~~~~~~~~~ To update all values in an array that match a query filter, use the all-positional operator -(``$[]``) in combination with the ``Set()`` method. +(``$[]``) with the ``Set()`` method. The following example uses the ``Set()`` method and the all-positional operator to update the ``Score`` property of all ``GradeEntry`` objects in the ``Grades`` array From 0fa1b544864b37ea5225366b9a4b17f936c400ab Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Mon, 2 Dec 2024 16:24:44 -0600 Subject: [PATCH 34/39] Apply suggestions from code review Co-authored-by: Jordan Smith <45415425+jordan-smith721@users.noreply.github.com> --- .../fundamentals/crud/write-operations/replace.txt | 12 ++++++------ .../crud/write-operations/update-many/arrays.txt | 6 ++++++ .../crud/write-operations/update-one/arrays.txt | 6 ++++++ source/includes/page-templates/update/update.rst | 7 +++---- 4 files changed, 21 insertions(+), 10 deletions(-) diff --git a/source/fundamentals/crud/write-operations/replace.txt b/source/fundamentals/crud/write-operations/replace.txt index f7ef7512..1b809456 100644 --- a/source/fundamentals/crud/write-operations/replace.txt +++ b/source/fundamentals/crud/write-operations/replace.txt @@ -21,7 +21,7 @@ Replace Documents Overview -------- -In this guide, you can learn how to use the {+driver-long+} to replace +In this guide, you can learn how to use the {+driver-short+} to replace documents in a MongoDB collection. The {+driver-short+} provides the ``ReplaceOne()`` and ``ReplaceOneAsync()`` methods. @@ -48,7 +48,7 @@ method. These methods accept the following parameters: * - ``filter`` - A *query filter* that specifies the document to replace. You can use the - ``Builders`` class to create a query filter.For more information about + ``Builders`` class to create a query filter. For more information about query filters, see the :manual:`{+mdb-server+} manual `. @@ -75,11 +75,11 @@ method. These methods accept the following parameters: The following code example demonstrates how to perform a replace operation. The code performs the following steps: -1. Uses the ``Builders`` class to create a query filter. The filter matches all +1. Creates a query filter by using the ``Builders`` class. The filter matches all documents where the ``cuisine`` field has the value ``"Pizza"``. #. Creates a new ``Restaurant`` object. #. Calls the ``ReplaceOne()`` method on the ``restaurants`` collection. This operation - find the first matching document in the collection and replaces it with the newly created + finds the first matching document in the collection and replaces it with the newly created document. Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the @@ -131,14 +131,14 @@ The ``ReplaceOptions`` class contains the following properties: * - ``BypassDocumentValidation`` - Specifies whether the replace operation bypasses document validation. This lets you replace documents that don't meet the schema validation requirements, if any - exist. See :manual:`the MongoDB server manual` + exist. See :manual:`the {+mdb-server+} manual ` for more information on schema validation. **Data Type:** ``bool?`` * - ``Collation`` - Specifies the kind of language collation to use when sorting - results. See :manual:`the MongoDB server manual` + results. See :manual:`the {+mdb-server+} manual ` for more information on collation. **Data Type:** `Collation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Collation.html>`__ diff --git a/source/fundamentals/crud/write-operations/update-many/arrays.txt b/source/fundamentals/crud/write-operations/update-many/arrays.txt index c4e80d71..97fe6afe 100644 --- a/source/fundamentals/crud/write-operations/update-many/arrays.txt +++ b/source/fundamentals/crud/write-operations/update-many/arrays.txt @@ -192,6 +192,7 @@ Update Arrays :dedent: :start-after: // start-update-many-pull :end-before: // end-update-many-pull + :emphasize-lines: 13-17 .. tab:: Asynchronous :tabid: update-many-pull-async @@ -202,6 +203,7 @@ Update Arrays :dedent: :start-after: // start-update-many-pull-async :end-before: // end-update-many-pull-async + :emphasize-lines: 13-17 .. replacement:: pullall-code-example-tabs @@ -216,6 +218,7 @@ Update Arrays :dedent: :start-after: // start-update-many-pullall :end-before: // end-update-many-pullall + :emphasize-lines: 15-20 .. tab:: Asynchronous :tabid: update-many-pullall-async @@ -226,6 +229,7 @@ Update Arrays :dedent: :start-after: // start-update-many-pullall-async :end-before: // end-update-many-pullall-async + :emphasize-lines: 15-20 .. replacement:: pullfilter-code-example-tabs @@ -240,6 +244,7 @@ Update Arrays :dedent: :start-after: // start-update-many-pullfilter :end-before: // end-update-many-pullfilter + :emphasize-lines: 15-19 .. tab:: Asynchronous :tabid: update-many-pullfilter-async @@ -250,6 +255,7 @@ Update Arrays :dedent: :start-after: // start-update-many-pullfilter-async :end-before: // end-update-many-pullfilter-async + :emphasize-lines: 15-20 .. replacement:: positional-code-example-tabs diff --git a/source/fundamentals/crud/write-operations/update-one/arrays.txt b/source/fundamentals/crud/write-operations/update-one/arrays.txt index e733ac44..ac015365 100644 --- a/source/fundamentals/crud/write-operations/update-one/arrays.txt +++ b/source/fundamentals/crud/write-operations/update-one/arrays.txt @@ -192,6 +192,7 @@ Update Arrays :dedent: :start-after: // start-update-one-pull :end-before: // end-update-one-pull + :emphasize-lines: 13-17 .. tab:: Asynchronous :tabid: update-one-pull-async @@ -202,6 +203,7 @@ Update Arrays :dedent: :start-after: // start-update-one-pull-async :end-before: // end-update-one-pull-async + :emphasize-lines: 13-17 .. replacement:: pullall-code-example-tabs @@ -216,6 +218,7 @@ Update Arrays :dedent: :start-after: // start-update-one-pullall :end-before: // end-update-one-pullall + :emphasize-lines: 15-20 .. tab:: Asynchronous :tabid: update-one-pullall-async @@ -226,6 +229,7 @@ Update Arrays :dedent: :start-after: // start-update-one-pullall-async :end-before: // end-update-one-pullall-async + :emphasize-lines: 15-20 .. replacement:: pullfilter-code-example-tabs @@ -240,6 +244,7 @@ Update Arrays :dedent: :start-after: // start-update-one-pullfilter :end-before: // end-update-one-pullfilter + :emphasize-lines: 15-19 .. tab:: Asynchronous :tabid: update-one-pullfilter-async @@ -250,6 +255,7 @@ Update Arrays :dedent: :start-after: // start-update-one-pullfilter-async :end-before: // end-update-one-pullfilter-async + :emphasize-lines: 15-19 .. replacement:: positional-code-example-tabs diff --git a/source/includes/page-templates/update/update.rst b/source/includes/page-templates/update/update.rst index f8794f88..816ad83b 100644 --- a/source/includes/page-templates/update/update.rst +++ b/source/includes/page-templates/update/update.rst @@ -44,7 +44,7 @@ The |sync-method| and |async-method| methods accept the following parameters: * - ``options`` - *Optional.* An instance of the ``UpdateOptions`` class that specifies the configuration for the update operation. The default value is ``null``. For a list - of available option, see :ref:`csharp-update-options`. + of available options, see :ref:`csharp-update-options`. **Data Type:** `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ @@ -202,9 +202,8 @@ The ``UpdateOptions`` class contains the following properties: Return Value ------------ -The |sync-method| returns an ``UpdateResult``, and the |async-method| -method returns an asynchronous -version of this type, a ``Task`` object. +The |sync-method| method returns an ``UpdateResult``, and the |async-method| +method returns a ``Task`` object. The ``UpdateResult`` class contains the following properties: .. list-table:: From b704c360f1955d4545936590ea71211f7f041032 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Tue, 3 Dec 2024 08:24:49 -0600 Subject: [PATCH 35/39] feedback --- .../fundamentals/crud/write-operations/replace.txt | 8 ++++---- .../crud/write-operations/update-many/arrays.txt | 8 ++++++++ .../crud/write-operations/update-one/arrays.txt | 8 ++++++++ .../code-examples/replace-one/ReplaceOneAsync.cs | 7 ++++++- source/includes/page-templates/update/arrays.rst | 4 +++- source/includes/page-templates/update/update.rst | 14 +++++++------- 6 files changed, 36 insertions(+), 13 deletions(-) diff --git a/source/fundamentals/crud/write-operations/replace.txt b/source/fundamentals/crud/write-operations/replace.txt index 1b809456..3aebc2c4 100644 --- a/source/fundamentals/crud/write-operations/replace.txt +++ b/source/fundamentals/crud/write-operations/replace.txt @@ -145,14 +145,14 @@ The ``ReplaceOptions`` class contains the following properties: * - ``Comment`` - Gets or sets the user-provided comment for the operation. - See :manual:`the MongoDB server manual` + See :manual:`the {+mdb-server+} manual` for more information. **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ * - ``Hint`` - Gets or sets the index to use to scan for documents. - See :manual:`the MongoDB server manual` + See :manual:`the {+mdb-server+} manual` for more information. **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ @@ -160,14 +160,14 @@ The ``ReplaceOptions`` class contains the following properties: * - ``IsUpsert`` - Specifies whether the replace operation performs an upsert operation if no documents match the query filter. - See :manual:`the MongoDB server manual ` + See :manual:`the {+mdb-server+} manual ` for more information. **Data Type:** ``bool`` * - ``Let`` - Gets or sets the let document. - See :manual:`the MongoDB server manual ` + See :manual:`the {+mdb-server+} manual ` for more information. **Data Type:** `BsonDocument <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonDocument.html>`__ diff --git a/source/fundamentals/crud/write-operations/update-many/arrays.txt b/source/fundamentals/crud/write-operations/update-many/arrays.txt index 97fe6afe..8cb54701 100644 --- a/source/fundamentals/crud/write-operations/update-many/arrays.txt +++ b/source/fundamentals/crud/write-operations/update-many/arrays.txt @@ -31,6 +31,14 @@ Update Arrays all matching documents + .. replacement:: pusheach-section-ref + + .. _csharp-update-many-arrays-pusheach: + + .. replacement:: pusheach-method-link + + :ref:`PushEach() ` + .. replacement:: update-page-link :ref:`` diff --git a/source/fundamentals/crud/write-operations/update-one/arrays.txt b/source/fundamentals/crud/write-operations/update-one/arrays.txt index ac015365..b6283c02 100644 --- a/source/fundamentals/crud/write-operations/update-one/arrays.txt +++ b/source/fundamentals/crud/write-operations/update-one/arrays.txt @@ -31,6 +31,14 @@ Update Arrays the matching document + .. replacement:: pusheach-section-ref + + .. _csharp-update-one-arrays-pusheach: + + .. replacement:: pusheach-method-link + + :ref:`PushEach() ` + .. replacement:: update-page-link :ref:`` diff --git a/source/includes/code-examples/replace-one/ReplaceOneAsync.cs b/source/includes/code-examples/replace-one/ReplaceOneAsync.cs index 2e3375ca..e3e79743 100644 --- a/source/includes/code-examples/replace-one/ReplaceOneAsync.cs +++ b/source/includes/code-examples/replace-one/ReplaceOneAsync.cs @@ -89,8 +89,13 @@ private static async Task ReplaceOneRestaurantAsyncWithOptions Borough = "Manhattan", }; + var options = new ReplaceOptions + { + BypassDocumentValidation = true + }; + // Asynchronously replaces the existing restaurant document with the new document - return await _restaurantsCollection.ReplaceOneAsync(filter, newPizzaRestaurant); + return await _restaurantsCollection.ReplaceOneAsync(filter, newPizzaRestaurant, options); // end-replace-one-async-with-options } diff --git a/source/includes/page-templates/update/arrays.rst b/source/includes/page-templates/update/arrays.rst index 2dc535c8..15c587c0 100644 --- a/source/includes/page-templates/update/arrays.rst +++ b/source/includes/page-templates/update/arrays.rst @@ -50,7 +50,7 @@ to the ``Grades`` array in |matching-document-or-documents|: .. tip:: Configure the Push Operation To add a value at a specific position in an array, or to sort or slice the array after - updating it, call the ``PushEach()`` method instead. + updating it, call the |pusheach-method-link| method instead. To add one value to the end of an array, *but only if it doesn't already exist in the array*, call the ``Builders.Update.AddToSet()`` method. @@ -83,6 +83,8 @@ the value already exists in the array, the update operation does nothing. |addtoset-code-example-tabs| +|pusheach-section-ref| + Add Multiple Values ------------------- diff --git a/source/includes/page-templates/update/update.rst b/source/includes/page-templates/update/update.rst index 816ad83b..49741885 100644 --- a/source/includes/page-templates/update/update.rst +++ b/source/includes/page-templates/update/update.rst @@ -150,7 +150,7 @@ The ``UpdateOptions`` class contains the following properties: * - ``ArrayFilters`` - Specifies which array elements to modify for an update operation on an array field. - See :manual:`the MongoDB server manual` + See :manual:`the {+mdb-server+} manual` for more information. **Data Type:** IEnumerable<`ArrayFilterDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ArrayFilterDefinition.html>`__> @@ -158,28 +158,28 @@ The ``UpdateOptions`` class contains the following properties: * - ``BypassDocumentValidation`` - Specifies whether the update operation bypasses document validation. This lets you update documents that don't meet the schema validation requirements, if any - exist. See :manual:`the MongoDB server manual` + exist. See :manual:`the {+mdb-server+} manual` for more information on schema validation. **Data Type:** ``bool?`` * - ``Collation`` - Specifies the kind of language collation to use when sorting - results. See :manual:`the MongoDB server manual` + results. See :manual:`the {+mdb-server+} manual` for more information on collation. **Data Type:** `Collation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Collation.html>`__ * - ``Comment`` - Gets or sets the user-provided comment for the operation. - See :manual:`the MongoDB server manual` + See :manual:`the {+mdb-server+} manual` for more information. **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ * - ``Hint`` - Gets or sets the index to use to scan for documents. - See :manual:`the MongoDB server manual` + See :manual:`the {+mdb-server+} manual` for more information. **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ @@ -187,14 +187,14 @@ The ``UpdateOptions`` class contains the following properties: * - ``IsUpsert`` - Specifies whether the update operation performs an upsert operation if no documents match the query filter. - See :manual:`the MongoDB server manual ` + See :manual:`the {+mdb-server+} manual ` for more information. **Data Type:** ``bool`` * - ``Let`` - Gets or sets the let document. - See :manual:`the MongoDB server manual ` + See :manual:`the {+mdb-server+} manual ` for more information. **Data Type:** `BsonDocument <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonDocument.html>`__ From e3b5628ff690fa1d89377f733de70788043d368b Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Tue, 3 Dec 2024 11:03:41 -0600 Subject: [PATCH 36/39] feedback --- .../write-operations/update-many/arrays.txt | 28 ++++++++++ .../write-operations/update-one/arrays.txt | 32 ++++++++++- .../code-examples/update-many/UpdateMany.cs | 4 +- .../code-examples/update-one/UpdateOne.cs | 4 +- .../includes/page-templates/update/arrays.rst | 53 ++++++++++--------- .../includes/page-templates/update/fields.rst | 4 +- ...update-arrays-positional-operator-note.rst | 3 ++ .../allpositional-linq-code-intro.rst | 3 ++ .../allpositional-operator-code-intro.rst | 3 ++ .../filteredpositional-linq-code-intro.rst | 3 ++ ...filteredpositional-operator-code-intro.rst | 3 ++ .../positional-linq-code-intro.rst | 5 ++ .../positional-operator-code-intro.rst | 5 ++ .../allpositional-linq-code-intro.rst | 3 ++ .../allpositional-operator-code-intro.rst | 3 ++ .../filteredpositional-linq-code-intro.rst | 3 ++ ...filteredpositional-operator-code-intro.rst | 3 ++ .../update-one/positional-linq-code-intro.rst | 5 ++ .../positional-operator-code-intro.rst | 5 ++ 19 files changed, 140 insertions(+), 32 deletions(-) create mode 100644 source/includes/update-arrays-positional-operator-note.rst create mode 100644 source/includes/update-many/allpositional-linq-code-intro.rst create mode 100644 source/includes/update-many/allpositional-operator-code-intro.rst create mode 100644 source/includes/update-many/filteredpositional-linq-code-intro.rst create mode 100644 source/includes/update-many/filteredpositional-operator-code-intro.rst create mode 100644 source/includes/update-many/positional-linq-code-intro.rst create mode 100644 source/includes/update-many/positional-operator-code-intro.rst create mode 100644 source/includes/update-one/allpositional-linq-code-intro.rst create mode 100644 source/includes/update-one/allpositional-operator-code-intro.rst create mode 100644 source/includes/update-one/filteredpositional-linq-code-intro.rst create mode 100644 source/includes/update-one/filteredpositional-operator-code-intro.rst create mode 100644 source/includes/update-one/positional-linq-code-intro.rst create mode 100644 source/includes/update-one/positional-operator-code-intro.rst diff --git a/source/fundamentals/crud/write-operations/update-many/arrays.txt b/source/fundamentals/crud/write-operations/update-many/arrays.txt index 8cb54701..3878c1f1 100644 --- a/source/fundamentals/crud/write-operations/update-many/arrays.txt +++ b/source/fundamentals/crud/write-operations/update-many/arrays.txt @@ -272,6 +272,8 @@ Update Arrays .. tab:: Positional Operator (Sync) :tabid: update-many-positional-sync + .. include:: /includes/update-many/positional-operator-code-intro.rst + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp :copyable: true @@ -279,9 +281,13 @@ Update Arrays :start-after: // start-update-many-positional :end-before: // end-update-many-positional + .. include:: /includes/update-arrays-positional-operator-note.rst + .. tab:: Positional Operator (Async) :tabid: update-many-positional-async + .. include:: /includes/update-many/positional-operator-code-intro.rst + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp :copyable: true @@ -289,9 +295,13 @@ Update Arrays :start-after: // start-update-many-positional-async :end-before: // end-update-many-positional-async + .. include:: /includes/update-arrays-positional-operator-note.rst + .. tab:: LINQ (Sync) :tabid: update-many-positional-linq-sync + .. include:: /includes/update-many/positional-linq-code-intro.rst + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp :copyable: true @@ -302,6 +312,8 @@ Update Arrays .. tab:: LINQ (Async) :tabid: update-many-positional-linq-async + .. include:: /includes/update-many/positional-linq-code-intro.rst + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp :copyable: true @@ -316,6 +328,8 @@ Update Arrays .. tab:: Positional Operator (Sync) :tabid: update-many-filteredpositional-sync + .. include:: /includes/update-many/filteredpositional-operator-code-intro.rst + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp :copyable: true @@ -326,6 +340,8 @@ Update Arrays .. tab:: Positional Operator (Async) :tabid: update-many-filteredpositional-async + .. include:: /includes/update-many/filteredpositional-operator-code-intro.rst + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp :copyable: true @@ -336,6 +352,8 @@ Update Arrays .. tab:: LINQ (Sync) :tabid: update-many-filteredpositional-linq-sync + .. include:: /includes/update-many/filteredpositional-linq-code-intro.rst + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp :copyable: true @@ -346,6 +364,8 @@ Update Arrays .. tab:: LINQ (Async) :tabid: update-many-filteredpositional-linq-async + .. include:: /includes/update-many/filteredpositional-linq-code-intro.rst + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp :copyable: true @@ -360,6 +380,8 @@ Update Arrays .. tab:: Positional Operator (Sync) :tabid: update-many-allpositional-sync + .. include:: /includes/update-many/allpositional-operator-code-intro.rst + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp :copyable: true @@ -370,6 +392,8 @@ Update Arrays .. tab:: Positional Operator (Async) :tabid: update-many-allpositional-async + .. include:: /includes/update-many/allpositional-operator-code-intro.rst + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp :copyable: true @@ -380,6 +404,8 @@ Update Arrays .. tab:: LINQ (Sync) :tabid: update-many-allpositional-linq-sync + .. include:: /includes/update-many/allpositional-linq-code-intro.rst + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp :copyable: true @@ -390,6 +416,8 @@ Update Arrays .. tab:: LINQ (Async) :tabid: update-many-allpositional-linq-async + .. include:: /includes/update-many/allpositional-linq-code-intro.rst + .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp :copyable: true diff --git a/source/fundamentals/crud/write-operations/update-one/arrays.txt b/source/fundamentals/crud/write-operations/update-one/arrays.txt index b6283c02..3379ba56 100644 --- a/source/fundamentals/crud/write-operations/update-one/arrays.txt +++ b/source/fundamentals/crud/write-operations/update-one/arrays.txt @@ -266,12 +266,14 @@ Update Arrays :emphasize-lines: 15-19 .. replacement:: positional-code-example-tabs - + .. tabs:: .. tab:: Positional Operator (Sync) :tabid: update-one-positional-sync + .. include:: /includes/update-one/positional-operator-code-intro.rst + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp :copyable: true @@ -279,9 +281,13 @@ Update Arrays :start-after: // start-update-one-positional :end-before: // end-update-one-positional + .. include:: /includes/update-arrays-positional-operator-note.rst + .. tab:: Positional Operator (Async) :tabid: update-one-positional-async - + + .. include:: /includes/update-one/positional-operator-code-intro.rst + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp :copyable: true @@ -289,9 +295,13 @@ Update Arrays :start-after: // start-update-one-positional-async :end-before: // end-update-one-positional-async + .. include:: /includes/update-arrays-positional-operator-note.rst + .. tab:: LINQ (Sync) :tabid: update-one-positional-linq-sync + .. include:: /includes/update-one/positional-linq-code-intro.rst + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp :copyable: true @@ -302,6 +312,8 @@ Update Arrays .. tab:: LINQ (Async) :tabid: update-one-positional-linq-async + .. include:: /includes/update-one/positional-linq-code-intro.rst + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp :copyable: true @@ -316,6 +328,8 @@ Update Arrays .. tab:: Positional Operator (Sync) :tabid: update-one-filteredpositional-sync + .. include:: /includes/update-many/filteredpositional-operator-code-intro.rst + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp :copyable: true @@ -326,6 +340,8 @@ Update Arrays .. tab:: Positional Operator (Async) :tabid: update-one-filteredpositional-async + .. include:: /includes/update-many/filteredpositional-operator-code-intro.rst + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp :copyable: true @@ -336,6 +352,8 @@ Update Arrays .. tab:: LINQ (Sync) :tabid: update-one-filteredpositional-linq-sync + .. include:: /includes/update-many/filteredpositional-linq-code-intro.rst + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp :copyable: true @@ -346,6 +364,8 @@ Update Arrays .. tab:: LINQ (Async) :tabid: update-one-filteredpositional-linq-async + .. include:: /includes/update-many/filteredpositional-linq-code-intro.rst + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp :copyable: true @@ -360,6 +380,8 @@ Update Arrays .. tab:: Positional Operator (Sync) :tabid: update-one-allpositional-sync + .. include:: /includes/update-one/allpositional-operator-code-intro.rst + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp :copyable: true @@ -370,6 +392,8 @@ Update Arrays .. tab:: Positional Operator (Async) :tabid: update-one-allpositional-async + .. include:: /includes/update-one/allpositional-operator-code-intro.rst + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp :copyable: true @@ -380,6 +404,8 @@ Update Arrays .. tab:: LINQ (Sync) :tabid: update-one-allpositional-linq-sync + .. include:: /includes/update-one/allpositional-linq-code-intro.rst + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp :copyable: true @@ -390,6 +416,8 @@ Update Arrays .. tab:: LINQ (Async) :tabid: update-one-allpositional-linq-async + .. include:: /includes/update-one/allpositional-linq-code-intro.rst + .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp :copyable: true diff --git a/source/includes/code-examples/update-many/UpdateMany.cs b/source/includes/code-examples/update-many/UpdateMany.cs index 56d3cdb7..e010110c 100644 --- a/source/includes/code-examples/update-many/UpdateMany.cs +++ b/source/includes/code-examples/update-many/UpdateMany.cs @@ -106,7 +106,7 @@ public static void CombineUpdates() var combinedUpdate = Builders.Update.Combine( Builders.Update.Set("cuisine", "French"), - Builders.Update.PopLast("grades") + Builders.Update.Unset("borough") ); _restaurantsCollection.UpdateMany(filter, combinedUpdate); @@ -121,7 +121,7 @@ public static async Task CombineUpdatesAsync() var combinedUpdate = Builders.Update.Combine( Builders.Update.Set("cuisine", "French"), - Builders.Update.PopLast("grades") + Builders.Update.Unset("borough") ); await _restaurantsCollection.UpdateManyAsync(filter, combinedUpdate); diff --git a/source/includes/code-examples/update-one/UpdateOne.cs b/source/includes/code-examples/update-one/UpdateOne.cs index a5c1a022..a4e57a60 100644 --- a/source/includes/code-examples/update-one/UpdateOne.cs +++ b/source/includes/code-examples/update-one/UpdateOne.cs @@ -99,7 +99,7 @@ public static void CombineUpdates() var combinedUpdate = Builders.Update.Combine( Builders.Update.Set("cuisine", "French"), - Builders.Update.PopLast("grades") + Builders.Update.Unset("borough") ); _restaurantsCollection.UpdateOne(filter, combinedUpdate); @@ -114,7 +114,7 @@ public static async Task CombineUpdatesAsync() var combinedUpdate = Builders.Update.Combine( Builders.Update.Set("cuisine", "French"), - Builders.Update.PopLast("grades") + Builders.Update.Unset("borough") ); await _restaurantsCollection.UpdateOneAsync(filter, combinedUpdate); diff --git a/source/includes/page-templates/update/arrays.rst b/source/includes/page-templates/update/arrays.rst index 15c587c0..e7f6e3e1 100644 --- a/source/includes/page-templates/update/arrays.rst +++ b/source/includes/page-templates/update/arrays.rst @@ -163,6 +163,11 @@ Because these values already exist in the array, the update operation does nothi Remove Values ------------- +The following sections explain how to remove values from an array field. + +First Value +~~~~~~~~~~~ + To remove the first value from an array, call the ``Builders.Update.PopFirst()`` method. This method accepts the following parameter: @@ -183,6 +188,9 @@ object from the ``Grades`` array in |matching-document-or-documents|: |popfirst-code-example-tabs| +Last Value +~~~~~~~~~~ + To remove the last value from an array, call the ``Builders.Update.PopLast()`` method: This method accepts the following parameter: @@ -203,6 +211,9 @@ object from the ``Grades`` array in |matching-document-or-documents|: |poplast-code-example-tabs| +All Instances of a Value +~~~~~~~~~~~~~~~~~~~~~~~~ + To remove all instances of a specific value from an array, call the ``Builders.Update.Pull()`` method. This method accepts the following parameters: @@ -228,6 +239,9 @@ a specific ``GradeEntry`` object from the ``Grades`` array in |matching-document |pull-code-example-tabs| +All Instances of Multiple Values +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + To remove all instances of more than one specific value from an array, call the ``Builders.Update.PullAll()`` method. This method accepts the following parameters: @@ -254,6 +268,9 @@ specific ``GradeEntry`` objects from the ``Grades`` array in |matching-document- |pullall-code-example-tabs| +All Values That Match a Condition +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + To remove all values that match a specific condition from an array, call the ``Builders.Update.PullFilter()`` method. This method accepts the following parameters: @@ -315,42 +332,30 @@ The following sections describe different ways to update matching values in an a First Matching Value ~~~~~~~~~~~~~~~~~~~~ -To update only the first value in an array that matches a query filter, use the -positional operator (``$``) with the ``Set()`` method. - -.. note:: - - To use the positional operator, the array field must be part of the query filter. - -The following example uses the ``Set()`` method and the positional operator to -update the ``Grades`` array in |matching-document-or-documents|. First, -it finds *only the first* ``GradeEntry`` object in the ``Grades`` array where the ``Grade`` property -has the value ``"A"``. Then, it updates the ``Score`` property of the first matching -``GradeEntry`` object to 100. +To update the first value in an array, you can use either the positional operator +(``$``) or LINQ syntax. +Select a :guilabel:`Positional Operator` or :guilabel:`LINQ` tab to +see the corresponding syntax. |positional-code-example-tabs| All Matching Values ~~~~~~~~~~~~~~~~~~~ -To update all values in an array that match a specified condition, use the filtered -positional operator (``$[]``) with the ``Set()`` method. - -The following example uses the ``Set()`` method and the filtered positional operator -to update the ``Score`` property of all matching -``GradeEntry`` objects in the ``Grades`` array to 100 in |matching-document-or-documents|: +To update all values in an array that match a specified condition, you can use either +the filtered positional operator (``$[]``) or LINQ syntax. +Select a :guilabel:`Positional Operator` or :guilabel:`LINQ` tab to +see the corresponding syntax. |filteredpositional-code-example-tabs| All Values ~~~~~~~~~~ -To update all values in an array that match a query filter, use the all-positional operator -(``$[]``) with the ``Set()`` method. - -The following example uses the ``Set()`` method and the all-positional operator -to update the ``Score`` property of all ``GradeEntry`` objects in the ``Grades`` array -to 100 in |matching-document-or-documents|: +To update all values in an array that match a query filter, you can use either the +all-positional operator (``$[]``) or LINQ syntax. +Select a :guilabel:`Positional Operator` or :guilabel:`LINQ` tab to +see the corresponding syntax. |allpositional-code-example-tabs| diff --git a/source/includes/page-templates/update/fields.rst b/source/includes/page-templates/update/fields.rst index 2c68c447..287228ca 100644 --- a/source/includes/page-templates/update/fields.rst +++ b/source/includes/page-templates/update/fields.rst @@ -108,8 +108,8 @@ method. This method accepts the following parameters: **Data Type:** ``TField`` -Set If Lower or Greater ------------------------ +Set by Comparison +----------------- To update the value of the field to a specified value, but only if the specified value is *greater than* the current value of the field, call the ``Builders.Update.Max()`` diff --git a/source/includes/update-arrays-positional-operator-note.rst b/source/includes/update-arrays-positional-operator-note.rst new file mode 100644 index 00000000..6f32e4ed --- /dev/null +++ b/source/includes/update-arrays-positional-operator-note.rst @@ -0,0 +1,3 @@ +.. note:: + + To use the positional operator, the array field must be part of the query filter. \ No newline at end of file diff --git a/source/includes/update-many/allpositional-linq-code-intro.rst b/source/includes/update-many/allpositional-linq-code-intro.rst new file mode 100644 index 00000000..64c05f28 --- /dev/null +++ b/source/includes/update-many/allpositional-linq-code-intro.rst @@ -0,0 +1,3 @@ +The following example uses the ``Set()`` and ``AllElements()`` methods +to update the ``Score`` property of all ``GradeEntry`` objects in the ``Grades`` array +to 100 in all matching documents. \ No newline at end of file diff --git a/source/includes/update-many/allpositional-operator-code-intro.rst b/source/includes/update-many/allpositional-operator-code-intro.rst new file mode 100644 index 00000000..623fc75b --- /dev/null +++ b/source/includes/update-many/allpositional-operator-code-intro.rst @@ -0,0 +1,3 @@ +The following example uses the ``Set()`` method and the all-positional operator +to update the ``Score`` property of all ``GradeEntry`` objects in the ``Grades`` array +to 100 in all matching documents. \ No newline at end of file diff --git a/source/includes/update-many/filteredpositional-linq-code-intro.rst b/source/includes/update-many/filteredpositional-linq-code-intro.rst new file mode 100644 index 00000000..fe4d031f --- /dev/null +++ b/source/includes/update-many/filteredpositional-linq-code-intro.rst @@ -0,0 +1,3 @@ +The following example uses the ``Set()`` and ``AllMatchingElements()`` methods +to update the ``Score`` property of all matching +``GradeEntry`` objects in the ``Grades`` array to 100 in all matching documents. \ No newline at end of file diff --git a/source/includes/update-many/filteredpositional-operator-code-intro.rst b/source/includes/update-many/filteredpositional-operator-code-intro.rst new file mode 100644 index 00000000..98823213 --- /dev/null +++ b/source/includes/update-many/filteredpositional-operator-code-intro.rst @@ -0,0 +1,3 @@ +The following example uses the ``Set()`` method and the filtered positional operator +to update the ``Score`` property of all matching +``GradeEntry`` objects in the ``Grades`` array to 100 in all matching documents. \ No newline at end of file diff --git a/source/includes/update-many/positional-linq-code-intro.rst b/source/includes/update-many/positional-linq-code-intro.rst new file mode 100644 index 00000000..5985bacb --- /dev/null +++ b/source/includes/update-many/positional-linq-code-intro.rst @@ -0,0 +1,5 @@ +The following example uses the ``Set()`` and ``FirstMatchingElement()`` methods to +update the ``Grades`` array in all matching documents. First, +it finds *only the first* ``GradeEntry`` object in the ``Grades`` array where the +``Grade`` property has the value ``"A"``. Then, it updates the ``Score`` property of +the first matching ``GradeEntry`` object to 100. \ No newline at end of file diff --git a/source/includes/update-many/positional-operator-code-intro.rst b/source/includes/update-many/positional-operator-code-intro.rst new file mode 100644 index 00000000..830f407a --- /dev/null +++ b/source/includes/update-many/positional-operator-code-intro.rst @@ -0,0 +1,5 @@ +The following example uses the ``Set()`` method and the positional operator to +update the ``Grades`` array in all matching documents. First, +it finds *only the first* ``GradeEntry`` object in the ``Grades`` array where the ``Grade`` +property has the value ``"A"``. Then, it updates the ``Score`` property of the first matching +``GradeEntry`` object to 100. \ No newline at end of file diff --git a/source/includes/update-one/allpositional-linq-code-intro.rst b/source/includes/update-one/allpositional-linq-code-intro.rst new file mode 100644 index 00000000..13cdf68e --- /dev/null +++ b/source/includes/update-one/allpositional-linq-code-intro.rst @@ -0,0 +1,3 @@ +The following example uses the ``Set()`` and ``AllElements()`` methods +to update the ``Score`` property of all ``GradeEntry`` objects in the ``Grades`` array +to 100 in the matching document. \ No newline at end of file diff --git a/source/includes/update-one/allpositional-operator-code-intro.rst b/source/includes/update-one/allpositional-operator-code-intro.rst new file mode 100644 index 00000000..2c340a4d --- /dev/null +++ b/source/includes/update-one/allpositional-operator-code-intro.rst @@ -0,0 +1,3 @@ +The following example uses the ``Set()`` method and the all-positional operator +to update the ``Score`` property of all ``GradeEntry`` objects in the ``Grades`` array +to 100 in the matching document. \ No newline at end of file diff --git a/source/includes/update-one/filteredpositional-linq-code-intro.rst b/source/includes/update-one/filteredpositional-linq-code-intro.rst new file mode 100644 index 00000000..a12559d6 --- /dev/null +++ b/source/includes/update-one/filteredpositional-linq-code-intro.rst @@ -0,0 +1,3 @@ +The following example uses the ``Set()`` and ``AllMatchingElements()`` methods +to update the ``Score`` property of all matching +``GradeEntry`` objects in the ``Grades`` array to 100 in the matching document. \ No newline at end of file diff --git a/source/includes/update-one/filteredpositional-operator-code-intro.rst b/source/includes/update-one/filteredpositional-operator-code-intro.rst new file mode 100644 index 00000000..cd2f4189 --- /dev/null +++ b/source/includes/update-one/filteredpositional-operator-code-intro.rst @@ -0,0 +1,3 @@ +The following example uses the ``Set()`` method and the filtered positional operator +to update the ``Score`` property of all matching +``GradeEntry`` objects in the ``Grades`` array to 100 in the matching document. \ No newline at end of file diff --git a/source/includes/update-one/positional-linq-code-intro.rst b/source/includes/update-one/positional-linq-code-intro.rst new file mode 100644 index 00000000..2d173256 --- /dev/null +++ b/source/includes/update-one/positional-linq-code-intro.rst @@ -0,0 +1,5 @@ +The following example uses the ``Set()`` and ``FirstMatchingElement()`` methods to +update the ``Grades`` array in the matching document. First, +it finds *only the first* ``GradeEntry`` object in the ``Grades`` array where the +``Grade`` property has the value ``"A"``. Then, it updates the ``Score`` property of +the first matching ``GradeEntry`` object to 100. \ No newline at end of file diff --git a/source/includes/update-one/positional-operator-code-intro.rst b/source/includes/update-one/positional-operator-code-intro.rst new file mode 100644 index 00000000..57579dab --- /dev/null +++ b/source/includes/update-one/positional-operator-code-intro.rst @@ -0,0 +1,5 @@ +The following example uses the ``Set()`` method and the positional operator to +update the ``Grades`` array in the matching document. First, +it finds *only the first* ``GradeEntry`` object in the ``Grades`` array where the ``Grade`` +property has the value ``"A"``. Then, it updates the ``Score`` property of the first matching +``GradeEntry`` object to 100. \ No newline at end of file From 38552b55d0f093cf33ead97c3df794297f68d840 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Wed, 4 Dec 2024 15:13:21 -0600 Subject: [PATCH 37/39] feedback --- .../crud/write-operations/replace.txt | 8 +-- .../crud/write-operations/update-many.txt | 8 +-- .../write-operations/update-many/arrays.txt | 60 +++++++++---------- .../crud/write-operations/update-one.txt | 8 +-- .../write-operations/update-one/arrays.txt | 60 +++++++++---------- 5 files changed, 72 insertions(+), 72 deletions(-) diff --git a/source/fundamentals/crud/write-operations/replace.txt b/source/fundamentals/crud/write-operations/replace.txt index 3aebc2c4..e64af0d9 100644 --- a/source/fundamentals/crud/write-operations/replace.txt +++ b/source/fundamentals/crud/write-operations/replace.txt @@ -88,7 +88,7 @@ corresponding code. .. tabs:: .. tab:: Synchronous - :tabid: replace-one-sync + :tabid: sync .. literalinclude:: /includes/code-examples/replace-one/ReplaceOne.cs :language: csharp @@ -98,7 +98,7 @@ corresponding code. :end-before: // end-replace-one .. tab:: Asynchronous - :tabid: replace-one-async + :tabid: async .. literalinclude:: /includes/code-examples/replace-one/ReplaceOneAsync.cs :language: csharp @@ -180,7 +180,7 @@ code. .. tabs:: .. tab:: Synchronous - :tabid: replace-one-sync-with-options + :tabid: sync .. literalinclude:: /includes/code-examples/replace-one/ReplaceOne.cs :language: csharp @@ -190,7 +190,7 @@ code. :end-before: // end-replace-one-sync-with-options .. tab:: Asynchronous - :tabid: replace-one-async-with-options + :tabid: async .. literalinclude:: /includes/code-examples/replace-one/ReplaceOneAsync.cs :language: csharp diff --git a/source/fundamentals/crud/write-operations/update-many.txt b/source/fundamentals/crud/write-operations/update-many.txt index d251dfae..e05203fd 100644 --- a/source/fundamentals/crud/write-operations/update-many.txt +++ b/source/fundamentals/crud/write-operations/update-many.txt @@ -82,7 +82,7 @@ Update Many .. tabs:: .. tab:: UpdateMany (Sync) - :tabid: update-many-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-many/UpdateMany.cs :language: csharp @@ -92,7 +92,7 @@ Update Many :end-before: // end-combine-sync .. tab:: UpdateMany (Async) - :tabid: update-many-async + :tabid: async .. literalinclude:: /includes/code-examples/update-many/UpdateMany.cs :language: csharp @@ -106,7 +106,7 @@ Update Many .. tabs:: .. tab:: UpdateMany (Sync) - :tabid: update-many-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-many/UpdateMany.cs :language: csharp @@ -116,7 +116,7 @@ Update Many :end-before: // end-pipeline-sync .. tab:: UpdateMany (Async) - :tabid: update-many-async + :tabid: async .. literalinclude:: /includes/code-examples/update-many/UpdateMany.cs :language: csharp diff --git a/source/fundamentals/crud/write-operations/update-many/arrays.txt b/source/fundamentals/crud/write-operations/update-many/arrays.txt index 3878c1f1..c09cc883 100644 --- a/source/fundamentals/crud/write-operations/update-many/arrays.txt +++ b/source/fundamentals/crud/write-operations/update-many/arrays.txt @@ -48,7 +48,7 @@ Update Arrays .. tabs:: .. tab:: Synchronous - :tabid: update-many-push-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp @@ -58,7 +58,7 @@ Update Arrays :end-before: // end-update-many-push .. tab:: Asynchronous - :tabid: update-many-push-async + :tabid: async .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp @@ -72,7 +72,7 @@ Update Arrays .. tabs:: .. tab:: Synchronous - :tabid: update-many-addtoset-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp @@ -82,7 +82,7 @@ Update Arrays :end-before: // end-update-many-addtoset .. tab:: Asynchronous - :tabid: update-many-addtoset-async + :tabid: async .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp @@ -96,7 +96,7 @@ Update Arrays .. tabs:: .. tab:: Synchronous - :tabid: update-many-pusheach-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp @@ -106,7 +106,7 @@ Update Arrays :end-before: // end-update-many-pusheach .. tab:: Asynchronous - :tabid: update-many-pusheach-async + :tabid: async .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp @@ -120,7 +120,7 @@ Update Arrays .. tabs:: .. tab:: Synchronous - :tabid: update-many-addtoset-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp @@ -130,7 +130,7 @@ Update Arrays :end-before: // end-update-many-addtoseteach .. tab:: Asynchronous - :tabid: update-many-addtoset-async + :tabid: async .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp @@ -144,7 +144,7 @@ Update Arrays .. tabs:: .. tab:: Synchronous - :tabid: update-many-popfirst-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp @@ -154,7 +154,7 @@ Update Arrays :end-before: // end-update-many-popfirst .. tab:: Asynchronous - :tabid: update-many-popfirst-async + :tabid: async .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp @@ -168,7 +168,7 @@ Update Arrays .. tabs:: .. tab:: Synchronous - :tabid: update-many-poplast-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp @@ -178,7 +178,7 @@ Update Arrays :end-before: // end-update-many-poplast .. tab:: Asynchronous - :tabid: update-many-poplast-async + :tabid: async .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp @@ -192,7 +192,7 @@ Update Arrays .. tabs:: .. tab:: Synchronous - :tabid: update-many-pull-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp @@ -203,7 +203,7 @@ Update Arrays :emphasize-lines: 13-17 .. tab:: Asynchronous - :tabid: update-many-pull-async + :tabid: async .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp @@ -218,7 +218,7 @@ Update Arrays .. tabs:: .. tab:: Synchronous - :tabid: update-many-pullall-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp @@ -229,7 +229,7 @@ Update Arrays :emphasize-lines: 15-20 .. tab:: Asynchronous - :tabid: update-many-pullall-async + :tabid: async .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp @@ -244,7 +244,7 @@ Update Arrays .. tabs:: .. tab:: Synchronous - :tabid: update-many-pullfilter-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp @@ -255,7 +255,7 @@ Update Arrays :emphasize-lines: 15-19 .. tab:: Asynchronous - :tabid: update-many-pullfilter-async + :tabid: async .. literalinclude:: /includes/code-examples/update-many/UpdateManyArrays.cs :language: csharp @@ -270,7 +270,7 @@ Update Arrays .. tabs:: .. tab:: Positional Operator (Sync) - :tabid: update-many-positional-sync + :tabid: sync .. include:: /includes/update-many/positional-operator-code-intro.rst @@ -284,7 +284,7 @@ Update Arrays .. include:: /includes/update-arrays-positional-operator-note.rst .. tab:: Positional Operator (Async) - :tabid: update-many-positional-async + :tabid: async .. include:: /includes/update-many/positional-operator-code-intro.rst @@ -298,7 +298,7 @@ Update Arrays .. include:: /includes/update-arrays-positional-operator-note.rst .. tab:: LINQ (Sync) - :tabid: update-many-positional-linq-sync + :tabid: linq-sync .. include:: /includes/update-many/positional-linq-code-intro.rst @@ -310,7 +310,7 @@ Update Arrays :end-before: // end-update-many-positional-linq .. tab:: LINQ (Async) - :tabid: update-many-positional-linq-async + :tabid: linq-async .. include:: /includes/update-many/positional-linq-code-intro.rst @@ -326,7 +326,7 @@ Update Arrays .. tabs:: .. tab:: Positional Operator (Sync) - :tabid: update-many-filteredpositional-sync + :tabid: sync .. include:: /includes/update-many/filteredpositional-operator-code-intro.rst @@ -338,7 +338,7 @@ Update Arrays :end-before: // end-update-many-filteredpositional .. tab:: Positional Operator (Async) - :tabid: update-many-filteredpositional-async + :tabid: async .. include:: /includes/update-many/filteredpositional-operator-code-intro.rst @@ -350,7 +350,7 @@ Update Arrays :end-before: // end-update-many-filteredpositional .. tab:: LINQ (Sync) - :tabid: update-many-filteredpositional-linq-sync + :tabid: linq-sync .. include:: /includes/update-many/filteredpositional-linq-code-intro.rst @@ -362,7 +362,7 @@ Update Arrays :end-before: // end-update-many-filteredpositional-linq .. tab:: LINQ (Async) - :tabid: update-many-filteredpositional-linq-async + :tabid: async .. include:: /includes/update-many/filteredpositional-linq-code-intro.rst @@ -378,7 +378,7 @@ Update Arrays .. tabs:: .. tab:: Positional Operator (Sync) - :tabid: update-many-allpositional-sync + :tabid: sync .. include:: /includes/update-many/allpositional-operator-code-intro.rst @@ -390,7 +390,7 @@ Update Arrays :end-before: // end-update-many-allpositional .. tab:: Positional Operator (Async) - :tabid: update-many-allpositional-async + :tabid: async .. include:: /includes/update-many/allpositional-operator-code-intro.rst @@ -402,7 +402,7 @@ Update Arrays :end-before: // end-update-many-allpositional-async .. tab:: LINQ (Sync) - :tabid: update-many-allpositional-linq-sync + :tabid: linq-sync .. include:: /includes/update-many/allpositional-linq-code-intro.rst @@ -414,7 +414,7 @@ Update Arrays :end-before: // end-update-many-allpositional-linq .. tab:: LINQ (Async) - :tabid: update-many-allpositional-linq-async + :tabid: linq-async .. include:: /includes/update-many/allpositional-linq-code-intro.rst diff --git a/source/fundamentals/crud/write-operations/update-one.txt b/source/fundamentals/crud/write-operations/update-one.txt index d0a1c428..192bf0ed 100644 --- a/source/fundamentals/crud/write-operations/update-one.txt +++ b/source/fundamentals/crud/write-operations/update-one.txt @@ -70,7 +70,7 @@ Update One .. tabs:: .. tab:: Synchronous - :tabid: update-one-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs :language: csharp @@ -80,7 +80,7 @@ Update One :end-before: // end-combine-sync .. tab:: Asynchronous - :tabid: update-one-async + :tabid: async .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs :language: csharp @@ -94,7 +94,7 @@ Update One .. tabs:: .. tab:: Synchronous - :tabid: update-one-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs :language: csharp @@ -104,7 +104,7 @@ Update One :end-before: // end-pipeline-sync .. tab:: Asynchronous - :tabid: update-one-async + :tabid: async .. literalinclude:: /includes/code-examples/update-one/UpdateOne.cs :language: csharp diff --git a/source/fundamentals/crud/write-operations/update-one/arrays.txt b/source/fundamentals/crud/write-operations/update-one/arrays.txt index 3379ba56..91ca58dc 100644 --- a/source/fundamentals/crud/write-operations/update-one/arrays.txt +++ b/source/fundamentals/crud/write-operations/update-one/arrays.txt @@ -48,7 +48,7 @@ Update Arrays .. tabs:: .. tab:: Synchronous - :tabid: update-one-push-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp @@ -58,7 +58,7 @@ Update Arrays :end-before: // end-update-one-push .. tab:: Asynchronous - :tabid: update-one-push-async + :tabid: async .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp @@ -72,7 +72,7 @@ Update Arrays .. tabs:: .. tab:: Synchronous - :tabid: update-one-addtoset-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp @@ -82,7 +82,7 @@ Update Arrays :end-before: // end-update-one-addtoset .. tab:: Asynchronous - :tabid: update-one-addtoset-async + :tabid: async .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp @@ -96,7 +96,7 @@ Update Arrays .. tabs:: .. tab:: Synchronous - :tabid: update-one-pusheach-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp @@ -106,7 +106,7 @@ Update Arrays :end-before: // end-update-one-pusheach .. tab:: Asynchronous - :tabid: update-one-pusheach-async + :tabid: async .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp @@ -120,7 +120,7 @@ Update Arrays .. tabs:: .. tab:: Synchronous - :tabid: update-one-addtoset-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp @@ -130,7 +130,7 @@ Update Arrays :end-before: // end-update-one-addtoseteach .. tab:: Asynchronous - :tabid: update-one-addtoset-async + :tabid: async .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp @@ -144,7 +144,7 @@ Update Arrays .. tabs:: .. tab:: Synchronous - :tabid: update-one-popfirst-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp @@ -154,7 +154,7 @@ Update Arrays :end-before: // end-update-one-popfirst .. tab:: Asynchronous - :tabid: update-one-popfirst-async + :tabid: async .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp @@ -168,7 +168,7 @@ Update Arrays .. tabs:: .. tab:: Synchronous - :tabid: update-one-poplast-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp @@ -178,7 +178,7 @@ Update Arrays :end-before: // end-update-one-poplast .. tab:: Asynchronous - :tabid: update-one-poplast-async + :tabid: async .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp @@ -192,7 +192,7 @@ Update Arrays .. tabs:: .. tab:: Synchronous - :tabid: update-one-pull-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp @@ -203,7 +203,7 @@ Update Arrays :emphasize-lines: 13-17 .. tab:: Asynchronous - :tabid: update-one-pull-async + :tabid: async .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp @@ -218,7 +218,7 @@ Update Arrays .. tabs:: .. tab:: Synchronous - :tabid: update-one-pullall-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp @@ -229,7 +229,7 @@ Update Arrays :emphasize-lines: 15-20 .. tab:: Asynchronous - :tabid: update-one-pullall-async + :tabid: async .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp @@ -244,7 +244,7 @@ Update Arrays .. tabs:: .. tab:: Synchronous - :tabid: update-one-pullfilter-sync + :tabid: sync .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp @@ -255,7 +255,7 @@ Update Arrays :emphasize-lines: 15-19 .. tab:: Asynchronous - :tabid: update-one-pullfilter-async + :tabid: async .. literalinclude:: /includes/code-examples/update-one/UpdateOneArrays.cs :language: csharp @@ -270,7 +270,7 @@ Update Arrays .. tabs:: .. tab:: Positional Operator (Sync) - :tabid: update-one-positional-sync + :tabid: sync .. include:: /includes/update-one/positional-operator-code-intro.rst @@ -284,7 +284,7 @@ Update Arrays .. include:: /includes/update-arrays-positional-operator-note.rst .. tab:: Positional Operator (Async) - :tabid: update-one-positional-async + :tabid: async .. include:: /includes/update-one/positional-operator-code-intro.rst @@ -298,7 +298,7 @@ Update Arrays .. include:: /includes/update-arrays-positional-operator-note.rst .. tab:: LINQ (Sync) - :tabid: update-one-positional-linq-sync + :tabid: linq-sync .. include:: /includes/update-one/positional-linq-code-intro.rst @@ -310,7 +310,7 @@ Update Arrays :end-before: // end-update-one-positional-linq .. tab:: LINQ (Async) - :tabid: update-one-positional-linq-async + :tabid: linq-async .. include:: /includes/update-one/positional-linq-code-intro.rst @@ -326,7 +326,7 @@ Update Arrays .. tabs:: .. tab:: Positional Operator (Sync) - :tabid: update-one-filteredpositional-sync + :tabid: sync .. include:: /includes/update-many/filteredpositional-operator-code-intro.rst @@ -338,7 +338,7 @@ Update Arrays :end-before: // end-update-one-filteredpositional .. tab:: Positional Operator (Async) - :tabid: update-one-filteredpositional-async + :tabid: async .. include:: /includes/update-many/filteredpositional-operator-code-intro.rst @@ -350,7 +350,7 @@ Update Arrays :end-before: // end-update-one-filteredpositional-async .. tab:: LINQ (Sync) - :tabid: update-one-filteredpositional-linq-sync + :tabid: linq-sync .. include:: /includes/update-many/filteredpositional-linq-code-intro.rst @@ -362,7 +362,7 @@ Update Arrays :end-before: // end-update-one-filteredpositional-linq .. tab:: LINQ (Async) - :tabid: update-one-filteredpositional-linq-async + :tabid: linq-async .. include:: /includes/update-many/filteredpositional-linq-code-intro.rst @@ -378,7 +378,7 @@ Update Arrays .. tabs:: .. tab:: Positional Operator (Sync) - :tabid: update-one-allpositional-sync + :tabid: sync .. include:: /includes/update-one/allpositional-operator-code-intro.rst @@ -390,7 +390,7 @@ Update Arrays :end-before: // end-update-one-allpositional .. tab:: Positional Operator (Async) - :tabid: update-one-allpositional-async + :tabid: async .. include:: /includes/update-one/allpositional-operator-code-intro.rst @@ -402,7 +402,7 @@ Update Arrays :end-before: // end-update-one-allpositional-async .. tab:: LINQ (Sync) - :tabid: update-one-allpositional-linq-sync + :tabid: linq-sync .. include:: /includes/update-one/allpositional-linq-code-intro.rst @@ -414,7 +414,7 @@ Update Arrays :end-before: // end-update-one-allpositional-linq .. tab:: LINQ (Async) - :tabid: update-one-allpositional-linq-async + :tabid: linq-async .. include:: /includes/update-one/allpositional-linq-code-intro.rst From 0d1e5f07b8dce64865ade6c056ff9fbf464bf527 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Wed, 4 Dec 2024 15:18:29 -0600 Subject: [PATCH 38/39] fix --- .../fundamentals/crud/write-operations/update-many/arrays.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/fundamentals/crud/write-operations/update-many/arrays.txt b/source/fundamentals/crud/write-operations/update-many/arrays.txt index c09cc883..1d8ebd59 100644 --- a/source/fundamentals/crud/write-operations/update-many/arrays.txt +++ b/source/fundamentals/crud/write-operations/update-many/arrays.txt @@ -362,7 +362,7 @@ Update Arrays :end-before: // end-update-many-filteredpositional-linq .. tab:: LINQ (Async) - :tabid: async + :tabid: linq-async .. include:: /includes/update-many/filteredpositional-linq-code-intro.rst From 57726f50d76cf7a719daaea86ff46798e508e098 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Thu, 19 Dec 2024 10:56:53 -0600 Subject: [PATCH 39/39] feedback --- .../crud/write-operations/update-many/arrays.txt | 4 ++-- .../code-examples/update-many/UpdateManyArrays.cs | 8 ++++---- .../includes/code-examples/update-one/UpdateOneArrays.cs | 8 ++++---- source/includes/page-templates/update/arrays.rst | 2 +- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/source/fundamentals/crud/write-operations/update-many/arrays.txt b/source/fundamentals/crud/write-operations/update-many/arrays.txt index 1d8ebd59..c3fe8399 100644 --- a/source/fundamentals/crud/write-operations/update-many/arrays.txt +++ b/source/fundamentals/crud/write-operations/update-many/arrays.txt @@ -346,8 +346,8 @@ Update Arrays :language: csharp :copyable: true :dedent: - :start-after: // start-update-many-filteredpositional - :end-before: // end-update-many-filteredpositional + :start-after: // start-update-many-filteredpositional-async + :end-before: // end-update-many-filteredpositional-async .. tab:: LINQ (Sync) :tabid: linq-sync diff --git a/source/includes/code-examples/update-many/UpdateManyArrays.cs b/source/includes/code-examples/update-many/UpdateManyArrays.cs index 7e757516..dcf2c2ac 100644 --- a/source/includes/code-examples/update-many/UpdateManyArrays.cs +++ b/source/includes/code-examples/update-many/UpdateManyArrays.cs @@ -532,7 +532,7 @@ public static UpdateResult UpdateManyFilteredPositional() // Set Grade = "A" in all GradeEntry objects where Score >= 94 var update = Builders.Update - .Set("grades.$[gradeEntry].grade", "F"); + .Set("grades.$[gradeEntry].grade", "A"); var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; var result = _restaurantsCollection.UpdateMany(filter, update, updateOptions); @@ -557,7 +557,7 @@ public static UpdateResult UpdateManyFilteredPositionalLinq() // Set Grade = "A" in all GradeEntry objects where Score >= 94 var update = Builders.Update - .Set(restaurant => restaurant.Grades.AllMatchingElements("gradeEntry").Score, 100); + .Set(restaurant => restaurant.Grades.AllMatchingElements("gradeEntry").Grade, "A"); var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; var result = _restaurantsCollection.UpdateMany(filter, update, updateOptions); @@ -582,7 +582,7 @@ public static async Task UpdateManyFilteredPositionalAsync() // Set Grade = "A" in all GradeEntry objects where Score >= 94 var update = Builders.Update - .Set("grades.$[gradeEntry].grade", "F"); + .Set("grades.$[gradeEntry].grade", "A"); var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; var result = await _restaurantsCollection.UpdateManyAsync(filter, update, updateOptions); @@ -607,7 +607,7 @@ public static async Task UpdateManyFilteredPositionalLinqAsync() // Set Grade = "A" in all GradeEntry objects where Score >= 94 var update = Builders.Update - .Set(restaurant => restaurant.Grades.AllMatchingElements("gradeEntry").Score, 100); + .Set(restaurant => restaurant.Grades.AllMatchingElements("gradeEntry").Grade, "A"); var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; var result = await _restaurantsCollection.UpdateManyAsync(filter, update, updateOptions); diff --git a/source/includes/code-examples/update-one/UpdateOneArrays.cs b/source/includes/code-examples/update-one/UpdateOneArrays.cs index 73a78a02..361ab0cc 100644 --- a/source/includes/code-examples/update-one/UpdateOneArrays.cs +++ b/source/includes/code-examples/update-one/UpdateOneArrays.cs @@ -530,7 +530,7 @@ public static UpdateResult UpdateOneFilteredPositional() // Set Grade = "A" in all GradeEntry objects where Score >= 94 var update = Builders.Update - .Set("grades.$[gradeEntry].grade", "F"); + .Set("grades.$[gradeEntry].grade", "A"); var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; var result = _restaurantsCollection.UpdateOne(filter, update, updateOptions); @@ -555,7 +555,7 @@ public static UpdateResult UpdateOneFilteredPositionalLinq() // Set Grade = "A" in all GradeEntry objects where Score >= 94 var update = Builders.Update - .Set(restaurant => restaurant.Grades.AllMatchingElements("gradeEntry").Score, 100); + .Set(restaurant => restaurant.Grades.AllMatchingElements("gradeEntry").Grade, "A"); var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; var result = _restaurantsCollection.UpdateOne(filter, update, updateOptions); @@ -580,7 +580,7 @@ public static async Task UpdateOneFilteredPositionalAsync() // Set Grade = "A" in all GradeEntry objects where Score >= 94 var update = Builders.Update - .Set("grades.$[gradeEntry].grade", "F"); + .Set("grades.$[gradeEntry].grade", "A"); var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; var result = await _restaurantsCollection.UpdateOneAsync(filter, update, updateOptions); @@ -605,7 +605,7 @@ public static async Task UpdateOneFilteredPositionalLinqAsync() // Set Grade = "A" in all GradeEntry objects where Score >= 94 var update = Builders.Update - .Set(restaurant => restaurant.Grades.AllMatchingElements("gradeEntry").Score, 100); + .Set(restaurant => restaurant.Grades.AllMatchingElements("gradeEntry").Grade, "A"); var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; var result = await _restaurantsCollection.UpdateOneAsync(filter, update, updateOptions); diff --git a/source/includes/page-templates/update/arrays.rst b/source/includes/page-templates/update/arrays.rst index e7f6e3e1..3a7e7521 100644 --- a/source/includes/page-templates/update/arrays.rst +++ b/source/includes/page-templates/update/arrays.rst @@ -232,7 +232,7 @@ To remove all instances of a specific value from an array, call the * - ``value`` - The value to remove from the array field. - **Data Type:** ``IEnumerable`` + **Data Type:** ``TItem`` The following code example uses the ``Pull()`` method to remove all instances of a a specific ``GradeEntry`` object from the ``Grades`` array in |matching-document-or-documents|: