==============================
MongoDB\\Collection::findOne()
==============================

.. default-domain:: mongodb
                    
.. contents:: On this page
   :local:
   :backlinks: none
   :depth: 1
   :class: singlecol

              
Definition
----------

.. phpmethod:: MongoDB\\Collection::findOne
   
   Finds a single document matching the query.
   
   .. code-block:: php
                   
      function findOne($filter = [], array $options = []): array|object

   ``findOne()`` supports the following parameters:
   
   .. include:: /includes/apiargs/MongoDBCollection-method-findOne-param.rst

   The ``$options`` parameter supports the following options:
                
   .. include:: /includes/apiargs/MongoDBCollection-method-findOne-option.rst

                
Output
------

Returns the :term:`first document <natural order>` that matches the
query or ``null`` if no document matches the query.

Examples
--------

The following example finds a restaurant 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.

.. code-block:: php
                
   $database = new MongoDB\Client;

   $collection = $database->selectCollection('example','restaurants');

   $restaurants = $collection->findOne(
       [ 'cuisine' => 'Italian', 'borough' => 'Manhattan'],
       [ 'limit' => 5, 
         'projection' => [
           'name' => 1, 'borough' => 1, 'cuisine' => 1,
         ],
       ]
   );

   
   foreach ($restaurants as $restaurant) {
      var_dump($restaurant);
   };

The output would resemble:

.. code-block:: none
                
   object(MongoDB\BSON\ObjectID)#11 (1) {
     ["oid"]=>
     string(24) "576023c6b02fa9281da3f983"
   }
   string(9) "Manhattan"
   string(7) "Italian"
   string(23) "Isle Of Capri Resturant"


.. seealso::
   
   - :phpmethod:`MongoDB\\Collection::findOne`
   - :manual:`find </reference/command/find>` command reference
     in the MongoDB manual
