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

.. default-domain:: mongodb

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

Definition
----------

16
.. phpmethod:: MongoDB\\Collection::deleteOne()
17

18 19 20
   Deletes at most one document that matches the filter criteria. If multiple
   documents match the filter criteria, only the :term:`first <natural order>`
   matching document will be deleted.
21 22 23 24 25

   .. code-block:: php

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

26
   This method has the following parameters:
27 28

   .. include:: /includes/apiargs/MongoDBCollection-method-deleteOne-param.rst
29 30

   The ``$options`` parameter supports the following options:
31 32 33

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

34 35
Return Values
-------------
36

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

40 41 42 43 44
Errors/Exceptions
-----------------

.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
45
.. include:: /includes/extracts/error-driver-bulkwriteexception.rst
46 47
.. include:: /includes/extracts/error-driver-runtimeexception.rst

48 49 50 51
Behavior
--------

.. include:: /includes/extracts/note-bson-comparison.rst
52
.. include:: /includes/extracts/bulkwriteexception-result.rst
53

54 55 56
Example
-------

57 58
The following example deletes one document in the ``users`` collection that has
has ``"ny"`` as the value for the ``state`` field:
59 60 61 62 63

.. code-block:: php

   <?php

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

77 78 79 80 81 82 83 84
See Also
--------

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