Skip to content

DOCSP-41970: Delete documents #128

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Sep 10, 2024
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
34 changes: 34 additions & 0 deletions source/includes/write/delete.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php
require 'vendor/autoload.php';

$uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your Atlas URI that connects to the sample dataset');
$client = new MongoDB\Client($uri);

// start-db-coll
$collection = $client->sample_restaurants->restaurants;
// end-db-coll

// Deletes a document that has a "name" value of "Ready Penny Inn"
// start-delete-one
$result = $collection->deleteOne(['name' => 'Ready Penny Inn']);
// end-delete-one

// Deletes documents that have a "borough" value of "Brooklyn"
// start-delete-many
$result = $collection->deleteMany(['borough' => 'Brooklyn']);
// end-delete-many

// Deletes matching documents and attaches a comment to the operation
// start-delete-options
$result = $collection->deleteMany(
['name' => new MongoDB\BSON\Regex('Mongo', '')],
Copy link
Member

Choose a reason for hiding this comment

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

If you're not using an options (i.e. regex flags), you can omit the optional second parameter:

Suggested change
['name' => new MongoDB\BSON\Regex('Mongo', '')],
['name' => new MongoDB\BSON\Regex('Mongo')],

Do other language docs use the BSON regex type or the $regex query operator? If we want to ensure consistency across all language examples, the operator might be the way to go.

The server docs note differences and point out where you'd need the BSON type; however, they're also written from the perspective of the shell where Javascript's RegExp (object or literal) is used and then serialized to a BSON type over the wire. RegExp has some of its own limitations (as do native regex types in other languages). In contrast, PHP has no native regex object and the MongoDB\BSON\Regex object is just a container for two strings (pattern and options), which serialize as-is to a BSON regex type (i.e. we can express anything the server supports).

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Good point, it's kind of a mix - the PyMongo and Go docs use $regex, and the Java sync and Reactive Streams docs use helper methods, for ex. So it wouldn't really help with consistency to change this example to use the $regex operator.

['comment' => 'Deleting Mongo restaurants'],
);
// end-delete-options

// Deletes and prints the number of documents that have a "cuisine" value of "Greek"
// start-delete-count
$result = $collection->deleteMany(['cuisine' => 'Greek']);
echo 'Deleted documents: ' . $result->getDeletedCount() . PHP_EOL;
// end-delete-count

11 changes: 11 additions & 0 deletions source/write.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
.. _php-write:

=====================
Write Data to MongoDB
=====================

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

/write/delete
197 changes: 197 additions & 0 deletions source/write/delete.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
.. _php-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 {+php-library+} 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 ``MongoDB\Collection::deleteOne()``
or ``MongoDB\Collection::deleteMany()`` methods.

Sample Data
~~~~~~~~~~~

The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants``
database from the :atlas:`Atlas sample datasets </sample-data>`. To access this collection
from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster
and assign the following value to your ``$collection`` variable:

.. literalinclude:: /includes/read/delete.php
:language: php
:dedent:
:start-after: start-db-coll
:end-before: end-db-coll

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.

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

You can perform delete operations by using the following methods:

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

Each delete method requires a **query filter** document, which specifies the
search criteria to 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
the ``restaurants`` collection that has a ``name`` value of ``'Ready Penny Inn'``:

.. literalinclude:: /includes/write/delete.php
:start-after: start-delete-one
:end-before: end-delete-one
:language: php
:dedent:

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

The following example uses the ``deleteMany()`` method to remove all documents
in the ``restaurants`` collection that have a ``borough`` value of ``'Brooklyn'``:

.. literalinclude:: /includes/write/delete.php
:start-after: start-delete-many
:end-before: end-delete-many
:language: php
:dedent:

Modify the Delete Operation
---------------------------

You can modify the behavior of the ``MongoDB\Collection::deleteOne()`` and
``MongoDB\Collection::deleteMany()`` methods by by passing an array that
specifies option values as a parameter. The following table describes the
options you can set in the array:

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

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

* - ``writeConcern``
- | Sets the write concern for the operation.
For more information, see :manual:`Write Concern </reference/write-concern/>`
in the {+mdb-server+} manual.

* - ``hint``
- | Gets or sets the index to scan for documents.
For more information, see the :manual:`hint statement </reference/command/delete/#std-label-deletes-array-hint>`
in the {+mdb-server+} manual.

* - ``let``
- | Specifies a document with a list of values to improve operation readability.
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.

* - ``session``
- | Specifies the client session to associate with the operation. For more
information, see :manual:`Session </reference/method/Session/>` in the
{+mdb-server+} manual.

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

Example
~~~~~~~

The following example calls the ``deleteMany()`` method to delete all documents in
the ``restaurants`` collection that have a ``name`` value containing the string ``'Mongo'``.
It also sets the ``comment`` option in an array parameter to add a comment to the
operation:

.. literalinclude:: /includes/write/delete.php
:start-after: start-delete-options
:end-before: end-delete-options
:language: php
:dedent:

.. note::

If you replace the ``deleteMany()`` method with ``deleteOne()`` in
the preceding example, the library deletes only the first document that has
a ``name`` value containing ``'Mongo'``.

Return Value
------------

The ``MongoDB\Collection::deleteOne()`` and ``MongoDB\Collection::deleteMany()``
methods return a ``MongoDB\DeleteResult`` object. This class contains the
following member functions:

- ``isAcknowledged()``, which returns a boolean indicating whether the operation
was acknowledged
- ``getDeletedCount()``, which returns the number of documents deleted

If the query filter does not match any documents, the driver doesn't delete any
documents and ``getDeletedCount()`` returns ``0``.

Example
~~~~~~~

The following example calls the ``deleteMany()`` method to delete documents
that have a ``cuisine`` value of ``'Greek'``. It then calls the ``getDeletedCount()``
member function to print the number of deleted documents:

.. io-code-block::
:copyable:

.. input:: /includes/write/delete.php
:start-after: start-delete-count
:end-before: end-delete-count
:language: php
:dedent:

.. output::
:visible: false

Deleted documents: 111

API Documentation
-----------------

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

- `MongoDB\\Collection::deleteOne() <{+api+}/method/MongoDBCollection-deleteOne/>`__
- `MongoDB\\Collection::deleteMany() <{+api+}/method/MongoDBCollection-deleteMany/>`__
- `MongoDB\\DeleteResult <{+api+}/class/MongoDBDeleteResult/>`__
Loading