MongoDBCollection-deleteMany.txt 2.11 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
=================================
MongoDB\\Collection::deleteMany()
=================================

.. default-domain:: mongodb

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

Definition
----------

16
.. phpmethod:: MongoDB\\Collection::deleteMany()
17 18 19 20 21 22 23

   Deletes all documents that match the filter criteria.

   .. code-block:: php

      function deleteMany($filter, array $options = []): MongoDB\DeleteResult

24
   This method has the following parameters:
25 26

   .. include:: /includes/apiargs/MongoDBCollection-method-deleteMany-param.rst
27 28

   The ``$options`` parameter supports the following options:
29 30 31

   .. include:: /includes/apiargs/MongoDBCollection-method-deleteMany-option.rst

32 33
Return Values
-------------
34

35 36
A :phpclass:`MongoDB\\DeleteResult` object, which encapsulates a
:php:`MongoDB\\Driver\\WriteResult <class.mongodb-driver-writeresult>` object.
37

38 39 40 41 42
Errors/Exceptions
-----------------

.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
43
.. include:: /includes/extracts/error-driver-bulkwriteexception.rst
44 45
.. include:: /includes/extracts/error-driver-runtimeexception.rst

46 47 48 49
Behavior
--------

.. include:: /includes/extracts/note-bson-comparison.rst
50
.. include:: /includes/extracts/bulkwriteexception-result.rst
51

52 53 54
Example
-------

55 56
The following example deletes all of the documents in the ``users`` collection
that have ``"ny"`` as the value for the ``state`` field:
57 58 59 60 61

.. code-block:: php

   <?php

62
   $collection = (new MongoDB\Client)->test->users;
63 64 65 66 67 68 69 70 71 72 73 74
   $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)

75 76 77 78 79 80 81 82
See Also
--------

- :phpmethod:`MongoDB\\Collection::deleteOne()`
- :phpmethod:`MongoDB\\Collection::bulkWrite()`
- :doc:`/tutorial/crud`
- :manual:`delete </reference/command/delete` command reference in the MongoDB
  manual