Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
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
3 changes: 2 additions & 1 deletion snooty.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,5 @@ version = "v{+version-number+}"
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"
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/"
35 changes: 35 additions & 0 deletions source/includes/write/delete.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import com.mongodb.client.model.DeleteOptions
import com.mongodb.client.model.Filters.*
import com.mongodb.kotlin.client.MongoClient

// start-data-class
data class Restaurant(val name: String, val borough: String)
// end-data-class

fun main() {
val uri = "<connection string>"

val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_restaurants")
val collection = database.getCollection<Movie>("restaurants")

// start-delete-one
val filter = eq(Restaurant::name.name, "Happy Garden")
val result = collection.deleteOne(filter)
// end-delete-one

// start-delete-many
val filter = and(
eq(Restaurant::name.name, "Happy Garden"),
eq(Restaurant::name.name, "Starbucks")
)
val result = collection.deleteMany(filter)
// end-delete-many

// start-delete-options
val opts = DeleteOptions().comment("sample comment")
val filter = regex(Restaurant::name.name, "Red")
val result = collection.deleteOne(filter, opts)
// end-delete-options

}
28 changes: 15 additions & 13 deletions source/write-operations.txt
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,18 @@ Write Data to MongoDB
:description: Learn how to use the Kotlin Sync driver to write data to MongoDB.
:keywords: usage examples, save, crud, create, code example

.. .. toctree::
.. :titlesonly:
.. :maxdepth: 1
.. toctree::
:titlesonly:
:maxdepth: 1

/write/delete

..
.. /write/insert
.. /write/update
.. /write/replace
.. /write/delete
.. /write/bulk-write
.. /write/gridfs
/write/insert
/write/update
/write/replace
/write/bulk-write
/write/gridfs

Overview
--------
Expand Down Expand Up @@ -149,8 +151,8 @@ collection:
:copyable:
:dedent:

.. To learn more about the ``delete_one()`` method, see the
.. :ref:`Delete Documents <kotlin-sync-write-delete>` guide.
To learn more about the ``deleteOne()`` method, see the
:ref:`Delete Documents <kotlin-sync-write-delete>` guide.

Delete Multiple
---------------
Expand All @@ -165,8 +167,8 @@ collection:
:copyable:
:dedent:

.. To learn more about the ``delete_many()`` method, see the
.. :ref:`Delete Documents <kotlin-sync-write-delete>` guide.
To learn more about the ``deleteMany()`` method, see the
:ref:`Delete Documents <kotlin-sync-write-delete>` guide.

Bulk Write
----------
Expand Down
202 changes: 202 additions & 0 deletions source/write/delete.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
.. _kotlin-sync-write-delete:

================
Delete Documents
================

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: remove, drop, code example

Overview
--------

In this guide, you can learn how to use the {+driver-short+} to remove
documents from a MongoDB collection by performing **delete operations**.

A delete operation removes one or more documents from a MongoDB collection.
You can perform a delete operation by using the ``deleteOne()`` or
``deleteMany()`` methods.

.. TODO .. tip:: Interactive Lab

.. This page includes a short interactive lab that demonstrates how to
.. modify data by using the ``deleteMany()`` 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 ``sample_restaurants.restaurants`` collection
from the :atlas:`Atlas sample datasets </sample-data>`.

.. TODO To learn how to create a
.. free MongoDB Atlas cluster and load the sample datasets, see the
.. :ref:`<kotlin-sync-get-started>` tutorial.

The documents in this collection are modeled by the following {+language+} data class:

.. literalinclude:: /includes/write/delete.kt
:start-after: start-data-class
:end-before: end-data-class
:language: kotlin
:copyable:
:dedent:

Delete Operations
-----------------

You can perform delete operations in MongoDB by using the following methods:

- ``deleteOne()``, which deletes *the first document* that matches the search criteria
- ``deleteMany()``, which deletes *all documents* that match the search criteria

Each delete method requires a **query filter** document, which specifies the
search criteria that determine which documents to select for removal.
For more information about query filters, see the
:manual:`Query Filter Documents section </core/document/#query-filter-documents>` in
the {+mdb-server+} manual.

Delete One Document
~~~~~~~~~~~~~~~~~~~

The following example uses the ``deleteOne()`` method to remove a
document in which the value of the ``name`` field is ``"Happy Garden"``:

.. literalinclude:: /includes/write/delete.kt
:start-after: start-delete-one
:end-before: end-delete-one
:language: kotlin
:copyable:
:dedent:

Delete Multiple Documents
~~~~~~~~~~~~~~~~~~~~~~~~~

The following example uses the ``deleteMany()`` method to remove all documents
in which the value of the ``borough`` field is ``"Brooklyn"`` and the
value of the ``name`` field is ``"Starbucks"``:

.. literalinclude:: /includes/write/delete.kt
:start-after: start-delete-many
:end-before: end-delete-many
:language: kotlin
:copyable:
:dedent:

Customize the Delete Operation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The ``deleteOne()`` and ``deleteMany()`` methods optionally accept a
``DeleteOptions`` parameter, which represents options you can use to
configure the delete operation. If you don't specify any additional

Check failure on line 105 in source/write/delete.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.ConciseTerms] 'more' is preferred over 'additional'. Raw Output: {"message": "[MongoDB.ConciseTerms] 'more' is preferred over 'additional'.", "location": {"path": "source/write/delete.txt", "range": {"start": {"line": 105, "column": 58}}}, "severity": "ERROR"}
options, the driver performs the delete operation with default settings.

The following table describes the setter methods that you can use to
configure a ``DeleteOptions`` instance:

.. list-table::
:widths: 30 70
:header-rows: 1

* - Property
- Description

* - ``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.

* - ``hint()``
- | Specifies the index to use when matching documents.
For more information, see the :manual:`hint statement </reference/command/delete/#std-label-deletes-array-hint>`
in the {+mdb-server+} manual.

* - ``hintString()``
- | Specifies the index as a string to use when matching documents.
For more information, see the :manual:`hint statement </reference/command/delete/#std-label-deletes-array-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/delete/#std-label-delete-let-syntax>` in the
{+mdb-server+} manual.

* - ``comment()``
- | Sets a comment to attach to the operation. For more
information, see the :manual:`delete command
fields </reference/command/delete/#command-fields>` guide in the
{+mdb-server+} manual for more information.

The following code creates options and uses the ``comment()`` method to
add a comment to the delete operation. Then, the example uses the
``deleteMany()`` method to delete all documents in the ``restaurants``
collection in which the value of the ``name`` field includes the string
``"Red"``.

.. literalinclude:: /includes/write/delete.kt
:start-after: start-delete-options
:end-before: end-delete-options
:language: kotlin
:copyable:
:dedent:

.. tip::

If the preceding example used the ``deleteOne()`` method instead of
the ``deleteMany()`` method, the driver would delete only the first

Check failure on line 163 in source/write/delete.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.AvoidSubjunctive] Avoid the subjunctive 'would'. Raw Output: {"message": "[MongoDB.AvoidSubjunctive] Avoid the subjunctive 'would'.", "location": {"path": "source/write/delete.txt", "range": {"start": {"line": 163, "column": 44}}}, "severity": "ERROR"}
document that matched the query filter.

Return Value
~~~~~~~~~~~~

The ``deleteOne()`` and ``deleteMany()`` methods each return a
``DeleteResult`` instance. You can access the following information from
a ``DeleteResult`` instance:

- ``deletedCount``, which indicates the number of documents deleted
- ``wasAcknowledged()``, which returns ``true`` if the server
acknowledges the result

If the query filter does not match any documents, the driver doesn't delete any
documents and the value of ``deletedCount`` is ``0``.

.. note::

If the ``wasAcknowledged()`` method returns ``false``, trying to
access the ``deletedCount`` property results in an
``InvalidOperation`` exception. The driver cannot
determine these values if the server does not acknowledge the write
operation.

API Documentation
~~~~~~~~~~~~~~~~~

To learn more about any of the methods or types discussed in this
guide, see the following API Documentation:

- `deleteOne() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/delete-one.html>`__
- `deleteMany() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/delete-many.html>`__
- `DeleteResult <{+core-api+}/com/mongodb/client/result/DeleteResult.html>`__

.. .. _kotlin-sync-delete-instruqt-lab:

.. .. instruqt:: /mongodb-docs/tracks/...
.. :title: deleteMany() Lesson
.. :drawer:
Loading