Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion snooty.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,4 @@ patch-version-number = "{+version-number+}.0"
mdb-server = "MongoDB Server"
stable-api = "Stable API"
api = "https://mongodb.github.io/mongo-java-driver/{+version-number+}/apidocs/mongodb-driver-kotlin-sync"
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"
2 changes: 1 addition & 1 deletion source/connect.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
45 changes: 45 additions & 0 deletions source/includes/write/update.kt
Original file line number Diff line number Diff line change
@@ -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 = "<connection string>"

val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_restaurants")
val collection = database.getCollection<Restaurant>("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
}
10 changes: 5 additions & 5 deletions source/write-operations.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 <kotlin-sync-write-update>` guide.
To learn more about the ``updateOne()`` method, see the
:ref:`Update Documents <kotlin-sync-write-update>` guide.

Update Multiple
---------------
Expand All @@ -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 <kotlin-sync-write-update>` guide.
To learn more about the ``updateMany()`` method, see the
:ref:`Update Documents <kotlin-sync-write-update>` guide.

Replace One
-----------
Expand Down
220 changes: 220 additions & 0 deletions source/write/update.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
.. _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 </sample-data>`. To learn how to create a
free MongoDB Atlas cluster and load the sample datasets, see the
:atlas:`Get Started with Atlas </getting-started>` 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 that should change. For a list of update

Check failure on line 58 in source/write/update.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.AvoidSubjunctive] Avoid the subjunctive 'should'. Raw Output: {"message": "[MongoDB.AvoidSubjunctive] Avoid the subjunctive 'should'.", "location": {"path": "source/write/update.txt", "range": {"start": {"line": 58, "column": 43}}}, "severity": "ERROR"}
operators and their usages, see the :manual:`Field Update Operators
guide page</reference/operator/update-field/>` 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:

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:

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 </reference/command/update/#std-label-update-command-upsert>`
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 </core/schema-validation/#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 </reference/collation/#std-label-collation>`
in the {+mdb-server+} manual.

* - ``arrayFilters()``
- | Contains a list of filters that specifies which array elements an update applies
to.

* - ``hint()``
- | Gets or sets the index to scan for documents.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Q: The intro to this section refers to this collection of methods as "setter methods" but this method in particular mentions getting OR setting. Does it make sense to discuss the get functionality of this method within the context of this table?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, copypasta error. This is only a set method in this driver, getHint() would be the getter. Will review the descriptions.

For more information, see the :manual:`hint statement </reference/command/update/#std-label-update-command-hint>`
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
</reference/command/update/#std-label-update-let-syntax>` in the
{+mdb-server+} manual.

* - ``comment()``
- | Sets a comment to attach to the operation. For more
information, see the :manual:`update command
fields </reference/command/update/#update>` 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 has the value ``"Sunrise Pizzeria"``. It then
sets the ``borough`` value in these documents 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 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:

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>`__
Loading