crud.txt 22 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
===============
CRUD Operations
===============

.. default-domain:: mongodb

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


CRUD operations *create*, *read*, *update*, and *delete* documents. The
15 16 17 18 19
|php-library|'s :phpclass:`MongoDB\\Collection` class implements MongoDB's
cross-driver `CRUD specification
<https://github.com/mongodb/specifications/blob/master/source/crud/crud.rst>`_,
providing access to methods for inserting, finding, updating, and deleting
documents in MongoDB.
20

21 22 23 24
This document provides a general introduction to inserting, querying, updating,
and deleting documents using the |php-library|. The MongoDB Manual's
:manual:`CRUD Section </crud>` provides a more thorough introduction to CRUD
operations with MongoDB.
25 26 27 28 29 30 31

Insert Documents
----------------

Insert One Document
~~~~~~~~~~~~~~~~~~~

32 33 34 35
The :phpmethod:`MongoDB\\Collection::insertOne()` method inserts a single
document into MongoDB and returns an instance of
:phpclass:`MongoDB\\InsertOneResult`, which you can use to access the ID of the
inserted document.
36

37
.. this uses the insertOne example from the method reference:
38

39 40 41
.. include:: /reference/method/MongoDBCollection-insertOne.txt
   :start-after: start-crud-include
   :end-before: end-crud-include
42

43
The output includes the ID of the inserted document.
44

45 46 47
If you include an ``_id`` value when inserting a document, MongoDB checks to
ensure that the ``_id`` value is unique for the collection. If the ``_id`` value
is not unique, the insert operation fails due to a duplicate key error.
48

49 50
The following example inserts a document while specifying the value for the
``_id``:
51 52 53 54 55

.. code-block:: php

   <?php

56
   $collection = (new MongoDB\Client)->test->users;
57 58 59 60 61 62 63 64 65 66 67 68

   $insertOneResult = $collection->insertOne(['_id' => 1, 'name' => 'Alice']);

   printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());

   var_dump($insertOneResult->getInsertedId());

The output would then resemble::

   Inserted 1 document(s)
   int(1)

69
.. seealso:: :phpmethod:`MongoDB\\Collection::insertOne()`
70 71 72 73

Insert Many Documents
~~~~~~~~~~~~~~~~~~~~~

74 75 76 77
The :phpmethod:`MongoDB\\Collection::insertMany()` method allows you to insert
multiple documents in one write operation and returns an instance of
:phpclass:`MongoDB\\InsertManyResult`, which you can use to access the IDs of
the inserted documents.
78 79 80 81 82 83 84

.. this uses the insertMany example from the method reference:

.. include:: /reference/method/MongoDBCollection-insertMany.txt
   :start-after: start-crud-include
   :end-before: end-crud-include

85
.. seealso:: :phpmethod:`MongoDB\\Collection::insertMany()`
86 87 88 89

Query Documents
---------------

90 91 92 93
The |php-library| provides the :phpmethod:`MongoDB\\Collection::findOne()` and
:phpmethod:`MongoDB\\Collection::find()` methods for querying documents and the
:phpmethod:`MongoDB\\Collection::aggregate()` method for performing
:manual:`aggregation operations </core/aggregation-pipeline>`.
94

95 96
.. include:: /includes/extracts/note-bson-comparison.rst

97 98 99
Find One Document
~~~~~~~~~~~~~~~~~

100 101 102
:phpmethod:`MongoDB\\Collection::findOne()` returns the :term:`first document
<natural order>` that matches the query or ``null`` if no document matches the
query.
103

104
The following example searches for the document with ``_id`` of ``"94301"``:
105 106 107 108 109

.. code-block:: php

   <?php

110
   $collection = (new MongoDB\Client)->test->zips;
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

   $document = $collection->findOne(['_id' => '94301']);

   var_dump($document);

The output would then resemble::

   object(MongoDB\Model\BSONDocument)#13 (1) {
     ["storage":"ArrayObject":private]=>
     array(5) {
       ["_id"]=>
       string(5) "94301"
       ["city"]=>
       string(9) "PALO ALTO"
       ["loc"]=>
       object(MongoDB\Model\BSONArray)#12 (1) {
         ["storage":"ArrayObject":private]=>
         array(2) {
           [0]=>
           float(-122.149685)
           [1]=>
           float(37.444324)
         }
       }
       ["pop"]=>
       int(15965)
       ["state"]=>
       string(2) "CA"
     }
   }

142 143 144 145 146 147
.. note::

   The criteria in this example matched an ``_id`` with a string value of
   ``"94301"``. The same criteria would not have matched a document with an
   integer value of ``94301`` due to MongoDB's :manual:`comparison rules for
   BSON types </reference/bson-type-comparison-order>`. Similarly, users should
148
   use a :php:`MongoDB\\BSON\\ObjectId <class.mongodb-bson-objectid>` object
149 150 151
   when matching an ``_id`` with an :manual:`ObjectId </reference/object-id/>`
   value, as strings and ObjectIds are not directly comparable.

152
.. seealso:: :phpmethod:`MongoDB\\Collection::findOne()`
153

154 155
.. _php-find-many-documents:

156 157 158
Find Many Documents
~~~~~~~~~~~~~~~~~~~

159 160 161
:phpmethod:`MongoDB\\Collection::find()` returns a
:php:`MongoDB\\Driver\\Cursor <mongodb-driver-cursor>` object, which you can
iterate upon to access all matched documents.
162

163 164
The following example lists the documents in the ``zips`` collection with the
specified city and state values:
165 166

.. code-block:: php
167

168 169
   <?php

170
   $collection = (new MongoDB\Client)->test->zips;
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186

   $cursor = $collection->find(['city' => 'JERSEY CITY', 'state' => 'NJ']);

   foreach ($cursor as $document) {
       echo $document['_id'], "\n";
   }

The output would resemble::

   07302
   07304
   07305
   07306
   07307
   07310

187
.. seealso:: :phpmethod:`MongoDB\\Collection::find()`
188 189 190 191 192 193

.. _php-query-projection:

Query Projection
~~~~~~~~~~~~~~~~

194 195 196 197
By default, queries in MongoDB return all fields in matching documents. To limit
the amount of data that MongoDB sends to applications, you can include a
:manual:`projection document </tutorial/project-fields-from-query-results>` in
the query operation.
198

199
.. note::
200

201 202
   MongoDB includes the ``_id`` field by default unless you explicitly exclude
   it in a projection document.
203

204 205 206 207
The following example finds restaurants based on the ``cuisine`` and ``borough``
fields and uses a :manual:`projection
</tutorial/project-fields-from-query-results>` to limit the fields that are
returned. It also limits the results to 5 documents.
208 209 210 211 212

.. code-block:: php

   <?php

213
   $collection = (new MongoDB\Client)->test->restaurants;
214

215 216 217 218 219 220 221 222 223 224 225 226
   $cursor = $collection->find(
       [
           'cuisine' => 'Italian',
           'borough' => 'Manhattan',
       ],
       [
           'projection' => [
               'name' => 1,
               'borough' => 1,
               'cuisine' => 1,
           ],
           'limit' => 4,
227 228 229
       ]
   );

230
   foreach($cursor as $restaurant) {
231 232 233 234
      var_dump($restaurant);
   };

The output would then resemble::
235

236 237 238 239
   object(MongoDB\Model\BSONDocument)#10 (1) {
     ["storage":"ArrayObject":private]=>
     array(4) {
       ["_id"]=>
240
       object(MongoDB\BSON\ObjectId)#8 (1) {
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
         ["oid"]=>
         string(24) "576023c6b02fa9281da3f983"
       }
       ["borough"]=>
       string(9) "Manhattan"
       ["cuisine"]=>
       string(7) "Italian"
       ["name"]=>
       string(23) "Isle Of Capri Resturant"
     }
   }
   object(MongoDB\Model\BSONDocument)#13 (1) {
     ["storage":"ArrayObject":private]=>
     array(4) {
       ["_id"]=>
256
       object(MongoDB\BSON\ObjectId)#12 (1) {
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
         ["oid"]=>
         string(24) "576023c6b02fa9281da3f98d"
       }
       ["borough"]=>
       string(9) "Manhattan"
       ["cuisine"]=>
       string(7) "Italian"
       ["name"]=>
       string(18) "Marchis Restaurant"
     }
   }
   object(MongoDB\Model\BSONDocument)#8 (1) {
     ["storage":"ArrayObject":private]=>
     array(4) {
       ["_id"]=>
272
       object(MongoDB\BSON\ObjectId)#10 (1) {
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
         ["oid"]=>
         string(24) "576023c6b02fa9281da3f99b"
       }
       ["borough"]=>
       string(9) "Manhattan"
       ["cuisine"]=>
       string(7) "Italian"
       ["name"]=>
       string(19) "Forlinis Restaurant"
     }
   }
   object(MongoDB\Model\BSONDocument)#12 (1) {
     ["storage":"ArrayObject":private]=>
     array(4) {
       ["_id"]=>
288
       object(MongoDB\BSON\ObjectId)#13 (1) {
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
         ["oid"]=>
         string(24) "576023c6b02fa9281da3f9a8"
       }
       ["borough"]=>
       string(9) "Manhattan"
       ["cuisine"]=>
       string(7) "Italian"
       ["name"]=>
       string(22) "Angelo Of Mulberry St."
     }
   }

Limit, Sort, and Skip Options
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

304 305
In addition to :ref:`projection criteria <php-query-projection>`, you can
specify options to limit, sort, and skip documents during queries.
306

307 308
The following example uses the ``limit`` and ``sort`` options to query for the
five most populous zip codes in the United States:
309 310 311 312 313

.. code-block:: php

   <?php

314
   $collection = (new MongoDB\Client)->test->zips;
315 316 317 318 319 320 321 322 323 324

   $cursor = $collection->find(
       [],
       [
           'limit' => 5,
           'sort' => ['pop' => -1],
       ]
   );

   foreach ($cursor as $document) {
325
       printf("%s: %s, %s\n", $document['_id'], $document['city'], $document['state']);
326 327 328 329 330 331 332 333 334 335
   }

The output would then resemble::

   60623: CHICAGO, IL
   11226: BROOKLYN, NY
   10021: NEW YORK, NY
   10025: NEW YORK, NY
   90201: BELL GARDENS, CA

336 337 338 339 340 341 342 343 344 345 346 347 348 349
Regular Expressions
~~~~~~~~~~~~~~~~~~~

Filter criteria may include regular expressions, either by using the
:php:`MongoDB\\BSON\\Regex <mongodb-bson-regex>` class directory or the
:query:`$regex` operator.

The following example lists documents in the ``zips`` collection where the city
name starts with "garden" and the state is Texas:

.. code-block:: php

   <?php

350
   $collection = (new MongoDB\Client)->test->zips;
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377

   $cursor = $collection->find([
       'city' => new MongoDB\BSON\Regex('^garden', 'i'),
       'state' => 'TX',
   ]);

   foreach ($cursor as $document) {
      printf("%s: %s, %s\n", $document['_id'], $document['city'], $document['state']);
   }

The output would then resemble::

   78266: GARDEN RIDGE, TX
   79739: GARDEN CITY, TX
   79758: GARDENDALE, TX

An equivalent filter could be constructed using the :query:`$regex` operator:

.. code-block:: php

   [
       'city' => ['$regex' => '^garden', '$options' => 'i'],
       'state' => 'TX',
   ]

.. seealso:: :manual:`$regex </reference/operator/query/regex>` in the MongoDB manual

378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
Although MongoDB's regular expression syntax is not exactly the same as PHP's
:php:`PCRE <manual/en/book.pcre.php>` syntax, :php:`preg_quote() <preg_quote>`
may be used to escape special characters that should be matched as-is. The
following example finds restaurants whose name starts with "(Library)":

.. code-block:: php

   <?php

   $collection = (new MongoDB\Client)->test->restaurants;

   $cursor = $collection->find([
       'name' => new MongoDB\BSON\Regex('^' . preg_quote('(Library)')),
   ]);

393 394
.. _php-aggregation:

395 396 397
Complex Queries with Aggregation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

398 399 400 401
MongoDB's :manual:`Aggregation Framework </core/aggregation-pipeline>` allows
you to issue complex queries that filter, transform, and group collection data.
The |php-library|\'s :phpmethod:`MongoDB\\Collection::aggregate()` method
returns a :php:`Traversable <traversable>` object, which you can iterate upon to
402
access the results of the aggregation operation. Refer to the
403
:phpmethod:`MongoDB\\Collection::aggregate()` method's :ref:`behavior
404
reference <php-agg-method-behavior>` for more about the method's output.
405

406 407
The following example lists the 5 US states with the most zip codes associated
with them:
408 409 410 411 412

.. code-block:: php

   <?php

413
   $collection = (new MongoDB\Client)->test->zips;
414 415 416 417 418 419 420 421 422 423 424 425

   $cursor = $collection->aggregate([
       ['$group' => ['_id' => '$state', 'count' => ['$sum' => 1]]],
       ['$sort' => ['count' => -1]],
       ['$limit' => 5],
   ]);

   foreach ($cursor as $state) {
       printf("%s has %d zip codes\n", $state['_id'], $state['count']);
   }

The output would then resemble::
426

427 428 429 430 431 432
   TX has 1671 zip codes
   NY has 1595 zip codes
   CA has 1516 zip codes
   PA has 1458 zip codes
   IL has 1237 zip codes

433
.. seealso:: :phpmethod:`MongoDB\\Collection::aggregate()`
434 435 436 437 438 439 440

Update Documents
----------------

Update One Document
~~~~~~~~~~~~~~~~~~~

441 442 443 444
Use the :phpmethod:`MongoDB\\Collection::updateOne()` method to update a single
document matching a filter. :phpmethod:`MongoDB\\Collection::updateOne()`
returns a :phpclass:`MongoDB\\UpdateResult` object, which you can use to access
statistics about the update operation.
445

446 447 448 449
Update methods have two required parameters: the query filter that identifies
the document or documents to update, and an update document that specifies what
updates to perform. The :phpmethod:`MongoDB\\Collection::updateOne()` reference
describes each parameter in detail.
450 451

The following example inserts two documents into an empty ``users`` collection
452
in the ``test`` database using the :phpmethod:`MongoDB\\Collection::insertOne()`
453 454
method, and then updates the documents where the value for the ``state`` field
is ``"ny"`` to include a ``country`` field set to ``"us"``:
455 456 457 458 459

.. code-block:: php

   <?php

460
   $collection = (new MongoDB\Client)->test->users;
461 462 463 464 465 466 467 468 469 470 471 472 473
   $collection->drop();

   $collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
   $collection->insertOne(['name' => 'Alice', 'state' => 'ny']);
   $updateResult = $collection->updateOne(
       ['state' => 'ny'],
       ['$set' => ['country' => 'us']]
   );

   printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
   printf("Modified %d document(s)\n", $updateResult->getModifiedCount());

Since the update operation uses the
474 475
:phpmethod:`MongoDB\\Collection::updateOne()` method, which updates the first
document to match the filter criteria, the results would then resemble::
476 477 478 479

   Matched 1 document(s)
   Modified 1 document(s)

480 481 482
It is possible for a document to match the filter but *not be modified* by an
update, as is the case where the update sets a field's value to its existing
value, as in this example:
483 484 485 486 487

.. code-block:: php

   <?php

488
   $collection = (new MongoDB\Client)->test->users;
489 490 491 492 493 494 495 496 497 498 499
   $collection->drop();

   $collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
   $updateResult = $collection->updateOne(
       ['name' => 'Bob'],
       ['$set' => ['state' => 'ny']]
   );

   printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
   printf("Modified %d document(s)\n", $updateResult->getModifiedCount());

500 501
The number of matched documents and the number of *modified* documents would
therefore not be equal, and the output from the operation would resemble::
502 503 504 505 506 507

   Matched 1 document(s)
   Modified 0 document(s)

.. seealso::

508 509
   - :phpmethod:`MongoDB\\Collection::updateOne()`
   - :phpmethod:`MongoDB\\Collection::findOneAndUpdate()`
510 511 512 513

Update Many Documents
~~~~~~~~~~~~~~~~~~~~~

514 515 516
:phpmethod:`MongoDB\\Collection::updateMany()` updates one or more documents
matching the filter criteria and returns a :phpclass:`MongoDB\\UpdateResult`
object, which you can use to access statistics about the update operation.
517

518 519 520 521
Update methods have two required parameters: the query filter that identifies
the document or documents to update, and an update document that specifies what
updates to perform. The :phpmethod:`MongoDB\\Collection::updateMany()` reference
describes each parameter in detail.
522

523
The following example inserts three documents into an empty ``users`` collection
524
in the ``test`` database and then uses the :query:`$set` operator to update the
525 526
documents matching the filter criteria to include the ``country`` field with
value ``"us"``:
527 528 529 530 531

.. code-block:: php

   <?php

532
   $collection = (new MongoDB\Client)->test->users;
533 534 535 536 537 538 539 540 541 542 543 544 545
   $collection->drop();

   $collection->insertOne(['name' => 'Bob', 'state' => 'ny', 'country' => 'us']);
   $collection->insertOne(['name' => 'Alice', 'state' => 'ny']);
   $collection->insertOne(['name' => 'Sam', 'state' => 'ny']);
   $updateResult = $collection->updateMany(
       ['state' => 'ny'],
       ['$set' => ['country' => 'us']]
   );

   printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
   printf("Modified %d document(s)\n", $updateResult->getModifiedCount());

546 547 548 549 550
If an update operation results in no change to a document, such as setting the
value of the field to its current value, the number of modified documents can be
less than the number of *matched* documents. Since the update document with
``name`` of ``"Bob"`` results in no changes to the document, the output of the
operation therefore resembles::
551 552 553 554

   Matched 3 document(s)
   Modified 2 document(s)

555
.. seealso:: :phpmethod:`MongoDB\\Collection::updateMany()`
556 557 558 559

Replace Documents
~~~~~~~~~~~~~~~~~

560 561 562 563
Replacement operations are similar to update operations, but instead of updating
a document to include new fields or new field values, a replacement operation
replaces the entire document with a new document, but retains the original
document's ``_id`` value.
564

565 566 567 568
The :phpmethod:`MongoDB\\Collection::replaceOne()` method replaces a single
document that matches the filter criteria and returns an instance of
:phpclass:`MongoDB\\UpdateResult`, which you can use to access statistics about
the replacement operation.
569

570 571 572 573 574
:phpmethod:`MongoDB\\Collection::replaceOne()` has two required parameters: the
query filter that identifies the document or documents to replace, and a
replacement document that will replace the original document in MongoDB. The
:phpmethod:`MongoDB\\Collection::replaceOne()` reference describes each
parameter in detail.
575 576 577

.. important:: 

578 579 580 581 582
   Replacement operations replace all of the fields in a document except the
   ``_id`` value. To avoid accidentally overwriting or deleting desired fields,
   use the :phpmethod:`MongoDB\\Collection::updateOne()` or
   :phpmethod:`MongoDB\\Collection::updateMany()` methods to update individual
   fields in a document rather than replacing the entire document.
583

584
The following example inserts one document into an empty ``users`` collection in
585
the ``test`` database, and then replaces that document with a new one:
586 587 588 589 590

.. code-block:: php

   <?php

591
   $collection = (new MongoDB\Client)->test->users;
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
   $collection->drop();

   $collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
   $updateResult = $collection->replaceOne(
       ['name' => 'Bob'],
       ['name' => 'Robert', 'state' => 'ca']
   );

   printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
   printf("Modified %d document(s)\n", $updateResult->getModifiedCount());

The output would then resemble::

   Matched 1 document(s)
   Modified 1 document(s)

.. seealso:: 

610 611
   - :phpmethod:`MongoDB\\Collection::replaceOne()`
   - :phpmethod:`MongoDB\\Collection::findOneAndReplace()`
612 613 614 615 616

Upsert
~~~~~~

Update and replace operations support an :manual:`upsert
617 618 619 620
</tutorial/update-documents/#upsert-option>` option. When ``upsert`` is ``true``
*and* no documents match the specified filter, the operation creates a new
document and inserts it. If there *are* matching documents, then the operation
modifies or replaces the matching document or documents.
621 622

When a document is upserted, the ID is accessible via
623
:phpmethod:`MongoDB\\UpdateResult::getUpsertedId()`.
624

625 626
The following example uses :phpmethod:`MongoDB\\Collection::updateOne()` with
the ``upsert`` option set to ``true`` and an empty ``users`` collection in the
627
``test`` database, therefore inserting the document into the database:
628 629 630 631 632

.. code-block:: php

   <?php

633
   $collection = (new MongoDB\Client)->test->users;
634 635 636 637 638 639 640 641 642 643
   $collection->drop();

   $updateResult = $collection->updateOne(
       ['name' => 'Bob'],
       ['$set' => ['state' => 'ny']],
       ['upsert' => true]
   );

   printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
   printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
644 645 646 647 648 649 650
   printf("Upserted %d document(s)\n", $updateResult->getUpsertedCount());

   $upsertedDocument = $collection->findOne([
       '_id' => $updateResult->getUpsertedId(),
   ]);

   var_dump($upsertedDocument);
651 652 653 654 655

The output would then resemble::

   Matched 0 document(s)
   Modified 0 document(s)
656
   Upserted 1 document(s)
657 658 659 660
   object(MongoDB\Model\BSONDocument)#16 (1) {
     ["storage":"ArrayObject":private]=>
     array(3) {
       ["_id"]=>
661
       object(MongoDB\BSON\ObjectId)#15 (1) {
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
         ["oid"]=>
         string(24) "57509c4406d7241dad86e7c3"
       }
       ["name"]=>
       string(3) "Bob"
       ["state"]=>
       string(2) "ny"
     }
   }

Delete Documents
----------------

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

678
The :phpmethod:`MongoDB\\Collection::deleteOne()` method deletes a single
679
document that matches the filter criteria and returns a
680 681
:phpclass:`MongoDB\\DeleteResult`, which you can use to access statistics about
the delete operation.
682

683 684 685
If multiple documents match the filter criteria,
:phpmethod:`MongoDB\\Collection::deleteOne()` deletes the :term:`first
<natural order>` matching document.
686

687 688 689 690
:phpmethod:`MongoDB\\Collection::deleteOne()` has one required parameter: a
query filter that specifies the document to delete. Refer to the
:phpmethod:`MongoDB\\Collection::deleteOne()` reference for full method
documentation.
691

692 693
The following operation deletes the first document where the ``state`` field's
value is ``"ny"``:
694 695 696 697 698

.. code-block:: php

   <?php

699
   $collection = (new MongoDB\Client)->test->users;
700 701 702 703 704 705 706 707 708 709 710 711
   $collection->drop();

   $collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
   $collection->insertOne(['name' => 'Alice', 'state' => 'ny']);
   $deleteResult = $collection->deleteOne(['state' => 'ny']);

   printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount());

The output would then resemble::

   Deleted 1 document(s)

712
.. seealso:: :phpmethod:`MongoDB\\Collection::deleteOne()`
713 714 715 716

Delete Many Documents
~~~~~~~~~~~~~~~~~~~~~

717 718 719
:phpmethod:`MongoDB\\Collection::deleteMany()` deletes all of the documents that
match the filter criteria and returns a :phpclass:`MongoDB\\DeleteResult`, which
you can use to access statistics about the delete operation.
720

721 722 723 724
:phpmethod:`MongoDB\\Collection::deleteMany()` has one required parameter: a
query filter that specifies the document to delete. Refer to the
:phpmethod:`MongoDB\\Collection::deleteMany()` reference for full method
documentation.
725

726 727
The following operation deletes all of the documents where the ``state`` field's
value is ``"ny"``:
728 729 730 731 732

.. code-block:: php

   <?php

733
   $collection = (new MongoDB\Client)->test->users;
734 735 736 737 738 739 740 741 742 743 744 745
   $collection->drop();

   $collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
   $collection->insertOne(['name' => 'Alice', 'state' => 'ny']);
   $deleteResult = $collection->deleteMany(['state' => 'ny']);

   printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount());

The output would then resemble::

   Deleted 2 document(s)

746
.. seealso:: :phpmethod:`MongoDB\\Collection::deleteMany()`