diff --git a/snooty.toml b/snooty.toml index 5eed4e15..9e1e3f44 100644 --- a/snooty.toml +++ b/snooty.toml @@ -27,4 +27,4 @@ mdb-server = "MongoDB Server" stable-api = "Stable API" api = "https://mongodb.github.io/mongo-java-driver/{+version-number+}/apidocs/mongodb-driver-kotlin-sync" kotlin-docs = "https://kotlinlang.org" -core-api = "https://mongodb.github.io/mongo-java-driver/{+version-number+}/apidocs/mongodb-driver-core/" +core-api = "https://mongodb.github.io/mongo-java-driver/{+version-number+}/apidocs/mongodb-driver-core" diff --git a/source/connect.txt b/source/connect.txt index 63f450d2..288ad111 100644 --- a/source/connect.txt +++ b/source/connect.txt @@ -53,7 +53,7 @@ Be sure to replace all placeholders in the code examples, such as .. include:: /includes/usage-examples/sample-app-intro.rst .. literalinclude:: /includes/usage-examples/connect-sample-app.kt - :language: python + :language: kotlin :copyable: true :linenos: :emphasize-lines: 6-8 diff --git a/source/includes/write/update.kt b/source/includes/write/update.kt new file mode 100644 index 00000000..b546b385 --- /dev/null +++ b/source/includes/write/update.kt @@ -0,0 +1,45 @@ +import com.mongodb.client.model.Filters.* +import com.mongodb.client.model.UpdateOptions +import com.mongodb.client.model.Updates.* +import com.mongodb.kotlin.client.MongoClient +import org.bson.Document + +// start-data-class +data class Restaurant( + val name: String, + val borough: String, + val cuisine: String, + val address: Document +) +// end-data-class + +fun main() { + val uri = "" + + val mongoClient = MongoClient.create(uri) + val database = mongoClient.getDatabase("sample_restaurants") + val collection = database.getCollection("restaurants") + + // start-update-one + val filter = eq(Restaurant::name.name, "Happy Garden") + val update = set(Restaurant::name.name, "Mountain House") + val result = collection.updateOne(filter, update) + // end-update-one + + // start-update-many + val filter = eq(Restaurant::name.name, "Starbucks") + val update = rename(Restaurant::address.name, "location") + val result = collection.updateMany(filter, update) + // end-update-many + + // start-update-options + val opts = UpdateOptions().upsert(true) + val filter = eq(Restaurant::name.name, "Sunrise Pizzeria") + val update = combine( + set(Restaurant::borough.name, "Queens"), + set(Restaurant::cuisine.name, "Italian") + ) + + collection.updateOne(filter, update, opts) + // end-update-options +} \ No newline at end of file diff --git a/source/write-operations.txt b/source/write-operations.txt index d87bc4dd..593300b0 100644 --- a/source/write-operations.txt +++ b/source/write-operations.txt @@ -22,11 +22,11 @@ Write Data to MongoDB :titlesonly: :maxdepth: 1 + /write/update /write/delete .. /write/insert - /write/update /write/replace /write/bulk-write /write/gridfs @@ -103,8 +103,8 @@ collection by creating or editing a field: :copyable: :dedent: -.. To learn more about the ``update_one()`` method, see the -.. :ref:`Update Documents ` guide. +To learn more about the ``updateOne()`` method, see the +:ref:`Update Documents ` guide. Update Multiple --------------- @@ -119,8 +119,8 @@ collection by creating or editing a field: :copyable: :dedent: -.. To learn more about the ``update_many()`` method, see the -.. :ref:`Update Documents ` guide. +To learn more about the ``updateMany()`` method, see the +:ref:`Update Documents ` guide. Replace One ----------- diff --git a/source/write/update.txt b/source/write/update.txt new file mode 100644 index 00000000..8d2c32d4 --- /dev/null +++ b/source/write/update.txt @@ -0,0 +1,224 @@ +.. _kotlin-sync-write-update: + +================ +Update Documents +================ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: modify, change, operator, code example + +Overview +-------- + +In this guide, you can learn how to use the {+driver-short+} to update +documents in a MongoDB collection by using the ``updateOne()`` and +``updateMany()`` methods. + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``sample_restaurants.restaurants`` collection +from the :atlas:`Atlas sample datasets `. To learn how to create a +free MongoDB Atlas cluster and load the sample datasets, see the +:atlas:`Get Started with Atlas ` guide. + +The documents in this collection are modeled by the following {+language+} data class: + +.. literalinclude:: /includes/write/update.kt + :start-after: start-data-class + :end-before: end-data-class + :language: kotlin + :copyable: + :dedent: + +Update Operations +----------------- + +You can update documents in MongoDB by using the following methods: + +- ``updateOne()``, which updates *the first document* that matches the search criteria +- ``updateMany()``, which updates *all documents* that match the search criteria + +Each update method requires the following parameters: + +- **Query filter**, which matches which documents to update. To learn + more about query filters, see the :ref:`kotlin-sync-specify-query` + guide. + +- **Update document**, which specifies the update operator, or the kind of update to + perform, and the fields and values to be updated. For a list of update + operators and their usages, see the :manual:`Field Update Operators + guide page` in the {+mdb-server+} manual. + +Update One Document +~~~~~~~~~~~~~~~~~~~ + +The following example uses the ``updateOne()`` method to update the +``name`` value of a document from ``"Happy Garden"`` to ``"Mountain +House"``: + +.. literalinclude:: /includes/write/update.kt + :start-after: start-update-one + :end-before: end-update-one + :language: kotlin + :copyable: + :dedent: + +Update Many Documents +~~~~~~~~~~~~~~~~~~~~~ + +The following example uses the ``updateMany()`` method to update all documents +in which the ``name`` value is ``"Starbucks"``. The update renames the +``address`` field to ``location``. + +.. literalinclude:: /includes/write/update.kt + :start-after: start-update-many + :end-before: end-update-many + :language: kotlin + :copyable: + :dedent: + +Customize the Update Operation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The ``updateOne()`` and ``updateMany()`` methods optionally accept +a parameter that sets options to configure the update operation. +If you don't specify any options, the driver performs update +operations with default settings. + +The following table describes the setter methods that you can use to +configure an ``UpdateOptions`` instance: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Property + - Description + + * - ``upsert()`` + - | Specifies whether the update operation performs an upsert operation if no + documents match the query filter. For more information, see the :manual:`upsert + statement ` + in the {+mdb-server+} manual. + | Defaults to ``false`` + + * - ``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. For more information about schema validation, see :manual:`Schema + Validation ` in the MongoDB + Server manual. + | Defaults to ``false``. + + * - ``collation()`` + - | Specifies the kind of language collation to use when sorting + results. For more information, see :manual:`Collation ` + in the {+mdb-server+} manual. + + * - ``arrayFilters()`` + - | Provides a list of filters that you specify to select which + array elements the update applies to. + + * - ``hint()`` + - | Sets the index to use when matching documents. + For more information, see the :manual:`hint statement ` + in the {+mdb-server+} manual. + + * - ``let()`` + - | Provides a map of parameter names and values to set top-level + variables for the operation. Values must be constant or closed + expressions that don't reference document fields. For more information, + see the :manual:`let statement + ` in the + {+mdb-server+} manual. + + * - ``comment()`` + - | Sets a comment to attach to the operation. For more + information, see the :manual:`update command + fields ` guide in the + {+mdb-server+} manual for more information. + +Modify Update Example +````````````````````` + +The following code uses the ``updateOne()`` method to match documents +in which the ``name`` field value is ``"Sunrise Pizzeria"``. It then +sets the ``borough`` value in the first matching document to +``"Queens"`` and the ``cuisine`` value to ``"Italian"``. + +Because the ``upsert`` option is set to ``true``, the driver inserts a +new document that has the fields and values specified in the update +document if the query filter doesn't match any existing documents. + +.. literalinclude:: /includes/write/update.kt + :start-after: start-update-options + :end-before: end-update-options + :language: kotlin + :copyable: + :dedent: + +Return Value +~~~~~~~~~~~~ + +The ``updateOne()`` and ``updateMany()`` methods each return an ``UpdateResult`` +object. You can use the following methods to access information from +an ``UpdateResult`` instance: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Property + - Description + + * - ``getMatchedCount()`` + - | Indicates the number of documents that matched the query filter, regardless of + how many updates were performed. + + * - ``getModifiedCount()`` + - | Indicates number of documents modified by the update operation. If an updated + document is identical to the original, it is not included in this + count. + + * - ``wasAcknowledged()`` + - | Returns ``true`` if the server acknowledged the result. + + * - ``getUpsertedId()`` + - | Specifies the ``_id`` value of the document that was upserted + in the database, if the driver performed an upsert. + +.. note:: + + If the ``wasAcknowledged()`` method returns ``false``, trying to + access other information from the ``UpdateResult`` instance results in an + ``InvalidOperation`` exception. The driver cannot + determine these values if the server does not acknowledge the write + operation. + +Additional Information +---------------------- + +To view runnable code examples that demonstrate how to updates documents by +using the {+driver-short+}, see :ref:`kotlin-sync-write`. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- `updateOne() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/update-one.html>`__ +- `updateMany() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/update-many.html>`__ +- `UpdateOptions <{+core-api+}/com/mongodb/client/model/UpdateOptions.html>`__ +- `UpdateResult <{+core-api+}/com/mongodb/client/result/UpdateResult.html>`__