MongoDBDatabase-selectCollection.txt 1.85 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
=====================================
MongoDB\\Database::selectCollection()
=====================================

.. default-domain:: mongodb

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

Definition
----------

16 17 18
.. phpmethod:: MongoDB\\Database::selectCollection()

   Selects a collection within the database.
19 20

   .. code-block:: php
21

22
      function selectCollection($collectionName, array $options = []): MongoDB\Collection
23

24
   This method has the following parameters:
25

26
   .. include:: /includes/apiargs/MongoDBDatabase-method-selectCollection-param.rst
27 28 29

   The ``$options`` parameter supports the following options:

30 31
   .. include:: /includes/apiargs/MongoDBDatabase-method-selectCollection-option.rst

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

35
A :phpclass:`MongoDB\\Collection` object.
36

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

.. include:: /includes/extracts/error-invalidargumentexception.rst

42 43
Behavior
--------
44

45 46 47
The selected collection inherits options such as read preference and type
mapping from the :phpclass:`Database <MongoDB\\Database>` object. Options may be
overridden via the ``$options`` parameter.
48 49 50 51

Example
-------

52
The following example selects the ``users`` collection in the ``test`` database:
53 54 55 56 57

.. code-block:: php

   <?php

58
   $db = (new MongoDB\Client)->test;
59

Mickaël's avatar
Mickaël committed
60
   $collection = $db->selectCollection('users');
61

62
The following example selects the ``users`` collection in the ``test``
63 64 65 66
database with a custom read preference:

.. code-block:: php

67 68
   <?php

69
   $db = (new MongoDB\Client)->test;
70 71

   $users = $db->selectCollection(
72 73 74 75
       'users',
       [
           'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
       ]
76 77
   );

78 79
See Also
--------
80

81 82 83
- :phpmethod:`MongoDB\\Database::__get()`
- :phpmethod:`MongoDB\\Client::selectCollection()`
- :phpmethod:`MongoDB\\Collection::__construct()`