Skip to content

Commit b9825a1

Browse files
authored
DOCSP-41970: Delete documents (#128)
Adds a guide that shows how to delete documents.
1 parent 3362eb1 commit b9825a1

File tree

3 files changed

+234
-0
lines changed

3 files changed

+234
-0
lines changed

source/includes/write/delete.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<?php
2+
require 'vendor/autoload.php';
3+
4+
$uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your Atlas URI that connects to the sample dataset');
5+
$client = new MongoDB\Client($uri);
6+
7+
// start-db-coll
8+
$collection = $client->sample_restaurants->restaurants;
9+
// end-db-coll
10+
11+
// Deletes a document that has a "name" value of "Ready Penny Inn"
12+
// start-delete-one
13+
$collection->deleteOne(['name' => 'Ready Penny Inn']);
14+
// end-delete-one
15+
16+
// Deletes documents that have a "borough" value of "Brooklyn"
17+
// start-delete-many
18+
$collection->deleteMany(['borough' => 'Brooklyn']);
19+
// end-delete-many
20+
21+
// Deletes matching documents and attaches a comment to the operation
22+
// start-delete-options
23+
$collection->deleteMany(
24+
['name' => new MongoDB\BSON\Regex('Mongo')],
25+
['comment' => 'Deleting Mongo restaurants'],
26+
);
27+
// end-delete-options
28+
29+
// Deletes and prints the number of documents that have a "cuisine" value of "Greek"
30+
// start-delete-count
31+
$result = $collection->deleteMany(['cuisine' => 'Greek']);
32+
echo 'Deleted documents: ' , $result->getDeletedCount() , PHP_EOL;
33+
// end-delete-count
34+

source/write.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ Write Data to MongoDB
88
:titlesonly:
99
:maxdepth: 1
1010

11+
/write/delete
1112
/write/replace
1213
/write/insert
1314
/write/update

source/write/delete.txt

Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
1+
.. _php-write-delete:
2+
3+
================
4+
Delete Documents
5+
================
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
.. facet::
14+
:name: genre
15+
:values: reference
16+
17+
.. meta::
18+
:keywords: remove, drop, code example
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to use the {+php-library+} to remove
24+
documents from a MongoDB collection by performing **delete operations**.
25+
26+
A delete operation removes one or more documents from a MongoDB collection.
27+
You can perform a delete operation by using the ``MongoDB\Collection::deleteOne()``
28+
or ``MongoDB\Collection::deleteMany()`` methods.
29+
30+
Sample Data
31+
~~~~~~~~~~~
32+
33+
The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants``
34+
database from the :atlas:`Atlas sample datasets </sample-data>`. To access this collection
35+
from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster
36+
and assign the following value to your ``$collection`` variable:
37+
38+
.. literalinclude:: /includes/write/delete.php
39+
:language: php
40+
:dedent:
41+
:start-after: start-db-coll
42+
:end-before: end-db-coll
43+
44+
To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the
45+
:atlas:`Get Started with Atlas </getting-started>` guide.
46+
47+
Delete Operations
48+
-----------------
49+
50+
You can perform delete operations by using the following methods:
51+
52+
- ``MongoDB\Collection::deleteOne()``, which deletes *the first document*
53+
that matches the search criteria
54+
- ``MongoDB\Collection::deleteMany()``, which deletes *all documents* that
55+
match the search criteria
56+
57+
Each delete method requires a **query filter** document, which specifies the
58+
search criteria to determine which documents to select for removal.
59+
For more information about query filters, see the
60+
:manual:`Query Filter Documents section </core/document/#query-filter-documents>` in
61+
the {+mdb-server+} manual.
62+
63+
Delete One Document
64+
~~~~~~~~~~~~~~~~~~~
65+
66+
The following example uses the ``deleteOne()`` method to remove a document in
67+
the ``restaurants`` collection that has a ``name`` value of ``'Ready Penny Inn'``:
68+
69+
.. literalinclude:: /includes/write/delete.php
70+
:start-after: start-delete-one
71+
:end-before: end-delete-one
72+
:language: php
73+
:dedent:
74+
75+
Delete Multiple Documents
76+
~~~~~~~~~~~~~~~~~~~~~~~~~
77+
78+
The following example uses the ``deleteMany()`` method to remove all documents
79+
in the ``restaurants`` collection that have a ``borough`` value of ``'Brooklyn'``:
80+
81+
.. literalinclude:: /includes/write/delete.php
82+
:start-after: start-delete-many
83+
:end-before: end-delete-many
84+
:language: php
85+
:dedent:
86+
87+
Modify the Delete Operation
88+
---------------------------
89+
90+
You can modify the behavior of the ``MongoDB\Collection::deleteOne()`` and
91+
``MongoDB\Collection::deleteMany()`` methods by passing an array that
92+
specifies option values as a parameter. The following table describes the
93+
options you can set in the array:
94+
95+
.. list-table::
96+
:widths: 30 70
97+
:header-rows: 1
98+
99+
* - Option
100+
- Description
101+
102+
* - ``collation``
103+
- | Specifies the kind of language collation to use when comparing
104+
strings. For more information, see :manual:`Collation </reference/collation/#std-label-collation>`
105+
in the {+mdb-server+} manual.
106+
107+
* - ``writeConcern``
108+
- | Sets the write concern for the operation. This option defaults to
109+
the collection's write concern.
110+
For more information, see :manual:`Write Concern </reference/write-concern/>`
111+
in the {+mdb-server+} manual.
112+
113+
* - ``hint``
114+
- | Gets or sets the index to scan for documents.
115+
For more information, see the :manual:`hint statement </reference/command/delete/#std-label-deletes-array-hint>`
116+
in the {+mdb-server+} manual.
117+
118+
* - ``let``
119+
- | Specifies a document with a list of values to improve operation readability.
120+
Values must be constant or closed expressions that don't reference document
121+
fields. For more information, see the :manual:`let statement
122+
</reference/command/delete/#std-label-delete-let-syntax>` in the
123+
{+mdb-server+} manual.
124+
125+
* - ``session``
126+
- | Specifies the client session to associate with the operation. For more
127+
information, see :manual:`Session </reference/method/Session/>` in the
128+
{+mdb-server+} manual.
129+
130+
* - ``comment``
131+
- | Attaches a comment to the operation. For more information, see the :manual:`delete command
132+
fields </reference/command/delete/#command-fields>` guide in the
133+
{+mdb-server+} manual.
134+
135+
Example
136+
~~~~~~~
137+
138+
The following example calls the ``deleteMany()`` method to delete all documents in
139+
the ``restaurants`` collection that have a ``name`` value containing the string ``'Mongo'``.
140+
It also sets the ``comment`` option in an array parameter to add a comment to the
141+
operation:
142+
143+
.. literalinclude:: /includes/write/delete.php
144+
:start-after: start-delete-options
145+
:end-before: end-delete-options
146+
:language: php
147+
:dedent:
148+
149+
.. note::
150+
151+
If you replace the ``deleteMany()`` method with ``deleteOne()`` in
152+
the preceding example, the library deletes only the first document that has
153+
a ``name`` value containing ``'Mongo'``.
154+
155+
Return Value
156+
------------
157+
158+
The ``MongoDB\Collection::deleteOne()`` and ``MongoDB\Collection::deleteMany()``
159+
methods return a ``MongoDB\DeleteResult`` object. This class contains the
160+
following member functions:
161+
162+
- ``isAcknowledged()``, which returns a boolean indicating whether the operation
163+
was acknowledged.
164+
- ``getDeletedCount()``, which returns the number of documents deleted. If the write
165+
operation was not acknowledged, this method throws an error.
166+
167+
If the query filter does not match any documents, the driver doesn't delete any
168+
documents and ``getDeletedCount()`` returns ``0``.
169+
170+
Example
171+
~~~~~~~
172+
173+
The following example calls the ``deleteMany()`` method to delete documents
174+
that have a ``cuisine`` value of ``'Greek'``. It then calls the ``getDeletedCount()``
175+
member function to print the number of deleted documents:
176+
177+
.. io-code-block::
178+
:copyable:
179+
180+
.. input:: /includes/write/delete.php
181+
:start-after: start-delete-count
182+
:end-before: end-delete-count
183+
:language: php
184+
:dedent:
185+
186+
.. output::
187+
:visible: false
188+
189+
Deleted documents: 111
190+
191+
API Documentation
192+
-----------------
193+
194+
To learn more about any of the methods or types discussed in this
195+
guide, see the following API documentation:
196+
197+
- `MongoDB\\Collection::deleteOne() <{+api+}/method/MongoDBCollection-deleteOne/>`__
198+
- `MongoDB\\Collection::deleteMany() <{+api+}/method/MongoDBCollection-deleteMany/>`__
199+
- `MongoDB\\DeleteResult <{+api+}/class/MongoDBDeleteResult/>`__

0 commit comments

Comments
 (0)