Skip to content

DOCSP-41963: Databases and collections #136

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
322 changes: 322 additions & 0 deletions source/databases-collections.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,322 @@
.. _php-databases-collections:

=========================
Databases and Collections
=========================

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

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: table, row, organize, storage, code example

Overview
--------

In this guide, you can learn how to use MongoDB databases and
collections with the {+php-library+}.

MongoDB organizes data into a hierarchy of the following levels:

- **Databases**: Top-level data structures in a MongoDB deployment that store collections.
- **Collections**: Groups of MongoDB documents. They are analogous to tables in relational databases.
- **Documents**: Units that store literal data such as string, numbers, dates, and other embedded documents.
For more information about document field types and structure, see the
:manual:`Documents </core/document/>` guide in the {+mdb-server+} manual.

Access a Database
-----------------

Access a database by passing the database name to the ``MongoDB\Client::selectDatabase()``
method.

The following example accesses a database named ``test_database``:

.. literalinclude:: /includes/databases-collections/databases-collections.php
:language: php
:dedent:
:start-after: start-access-database
:end-before: end-access-database

Alternatively, you can implicitly call the ``MongoDB\Client::__get()`` magic method on
a client object. This method allows you to select a database by using the syntax for
accessing a class property. The following example uses this shorthand syntax to access
the ``test_database`` database:

.. literalinclude:: /includes/databases-collections/databases-collections.php
:language: php
:dedent:
:start-after: start-access-database-short
:end-before: end-access-database-short

.. tip::

To learn more about ``__get()`` and PHP magic methods, see the following resources:

- :phpmethod:`MongoDB\Client::__get()` in the API documentation
- `Magic Methods <{+php-manual+}/language.oop5.magic.php>`__ in the PHP manual

.. _php-db-coll-access-collection:

Access a Collection
-------------------

Access a collection by using either of the following methods:

- ``MongoDB\Client::selectCollection()``: Pass the database and collection names as
parameters
- ``MongoDB\Database::selectCollection()``: Pass the collection name as a parameter

The following example accesses a collection named ``test_collection`` by using the
``MongoDB\Database::selectCollection()`` method:

.. literalinclude:: /includes/databases-collections/databases-collections.php
:language: php
:dedent:
:start-after: start-access-collection
:end-before: end-access-collection

.. tip::

If the provided collection name does not already exist in the database,
MongoDB implicitly creates the collection when you first insert data
into it.

Alternatively, you can implicitly call the ``MongoDB\Database::__get()`` magic method on
a database object. This method allows you to select a collection by using the syntax for
accessing a class property. The following example uses this shorthand syntax to access
the ``test_collection`` collection:

.. literalinclude:: /includes/databases-collections/databases-collections.php
:language: php
:dedent:
:start-after: start-access-collection-short
:end-before: end-access-collection-short

To learn more, see the :phpmethod:`MongoDB\Database::__get()`
API documentation.

.. _php-db-coll-create-collection:

Create a Collection
-------------------

Pass a collection name to the ``MongoDB\Database::createCollection()`` method to
explicitly create a collection in a MongoDB database.

The following example creates a collection named ``example_collection``:

.. literalinclude:: /includes/databases-collections/databases-collections.php
:language: php
:dedent:
:start-after: start-create-collection
:end-before: end-create-collection

You can specify collection options, such as maximum size and document
validation rules, by passing them as an array to the ``createCollection()`` method.
For a full list of optional parameters, see the `API documentation
<{+api+}/method/MongoDBDatabase-createCollection/#parameters>`__.

Get a List of Collections
-------------------------

You can query for a list of collections in a database by calling the
``MongoDB\Database::listCollections()`` method. The method returns a
cursor containing all collections in the database and their associated metadata.

The following example calls the ``listCollections()`` method and iterates over
the returned iterator to print the collections from the :ref:`php-db-coll-access-collection`
and :ref:`php-db-coll-create-collection` examples:

.. io-code-block::
:copyable:

.. input:: /includes/databases-collections/databases-collections.php
:language: php
:start-after: start-find-collections
:end-before: end-find-collections
:dedent:

.. output::
:language: console
:visible: false

MongoDB\Model\CollectionInfo Object
(
[name] => example_collection
[type] => collection
...
)
MongoDB\Model\CollectionInfo Object
(
[name] => test_collection
[type] => collection
...
)

Delete a Collection
-------------------

You can delete a collection from the database by using the ``MongoDB\Database::dropCollection()``
method.

The following example deletes the ``test_collection`` collection:

.. literalinclude:: /includes/databases-collections/databases-collections.php
:language: php
:dedent:
:start-after: start-drop-collection
:end-before: end-drop-collection

.. warning:: Dropping a Collection Deletes All Data in the Collection

Dropping a collection from your database permanently deletes all
documents and all indexes within that collection.

Drop a collection only if you no longer need the data in it.

.. _php-config-read-write:

Configure Read and Write Operations
-----------------------------------

You can control how the library routes read operations by setting a **read preference**.
You can also control options for how the library waits for acknowledgment of
read and write operations on a replica set by setting a **read concern** and a
**write concern**.

By default, databases inherit read and write settings from the ``MongoDB\Client``
instance. Collections inherit these settings from the ``MongoDB\Client`` or
``MongoDB\Database`` instance on which the ``selectCollection()`` method is called.
You can change these settings by passing an options array to the
``MongoDB\Client::selectDatabase()``, ``MongoDB\Client::selectCollection()``, or
``MongoDB\Database::selectCollection()`` methods.

To change the read preference, read concern, and write concern of your database
or collection, set the following options in the array parameter:

- ``readPreference``: Sets the read preference. For a list of available read
preferences, see :php:`MongoDB\Driver\ReadPreference <mongodb-driver-readpreference>`
in the extension API documentation.
- ``readConcern``: Sets the read concern. For a list of available read
concerns, see :php:`MongoDB\Driver\ReadConcern <mongodb-driver-readconcern>`
in the extension API documentation.
- ``writeConcern``: Sets the write concern. For a list of available write
concerns, see :php:`MongoDB\Driver\WriteConcern <mongodb-driver-writeconcern>`
in the extension API documentation.

.. tip::

To learn more about read preferences and read and write concerns, see the
following guides in the MongoDB Server manual:

- :manual:`Read Preference </core/read-preference/>`
- :manual:`Read Concern </reference/read-concern/>`
- :manual:`Write Concern </reference/write-concern/>`

Database Configuration Example
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The following example shows how to set the read preference, read concern, and
write concern of a database called ``test_database`` by passing an options
array to ``selectDatabase()``:

.. literalinclude:: /includes/databases-collections/databases-collections.php
:language: php
:dedent:
:start-after: start-database-settings
:end-before: end-database-settings

Collection Configuration Example
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The following example shows how to set the read preference, read concern, and
write concern of a collection called ``test_collection`` by passing an options
array to ``selectCollection()``:

.. literalinclude:: /includes/databases-collections/databases-collections.php
:language: php
:dedent:
:start-after: start-collection-settings
:end-before: end-collection-settings

Advanced Read Configurations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Tag Sets
````````

In {+mdb-server+}, you can apply key-value :manual:`tags
</core/read-preference-tags/>` to replica-set
members according to any criteria you choose. You can then use
those tags to target one or more members for a read operation.

By default, the {+php-library+} ignores tags when choosing a member
to read from. To instruct the {+php-library+} to prefer certain tags,
pass them as a parameter to your ``MongoDB\Driver\ReadPreference`` class
constructor. Then, set the ``MongoDB\Driver\ReadPreference`` object as
the value of the ``readPreference`` database option.

This code example sets the ``readPreference`` option to a tag set
that instructs ``test_database`` to prefer reads from secondary replica set
members in the following order:

1. Members from the New York data center (``['dc' => 'ny']``)
#. Members from the San Francisco data center (``['dc' => 'sf']``)
#. Any secondary members (``[]``)

.. literalinclude:: /includes/databases-collections/databases-collections.php
:language: php
:dedent:
:start-after: start-tag-set
:end-before: end-tag-set

Local Threshold
```````````````

If multiple replica-set members match the read preference and tag sets you specify,
the {+php-library+} reads from the nearest replica-set members, chosen according to
their ping time.

By default, the library uses only members whose ping times are within 15 milliseconds
of the nearest member for queries. To distribute reads between members with
higher latencies, pass an options array to the ``MongoDB\Client`` constructor that
sets the ``localThresholdMS`` option.

The following example specifies a local threshold of 35 milliseconds:

.. literalinclude:: /includes/databases-collections/databases-collections.php
:language: php
:dedent:
:start-after: start-local-threshold
:end-before: end-local-threshold

In the preceding example, the {+php-library+} distributes reads among matching members
within 35 milliseconds of the closest member's ping time.

.. note::

The {+php-library+} ignores the value of ``localThresholdMS`` when communicating with a
replica set through a ``mongos`` instance. In this case, use the
:manual:`localThreshold </reference/program/mongos/#std-option-mongos.--localThreshold>`
command-line option.

API Documentation
-----------------

To learn more about any of the methods or types discussed in this
guide, see the following API documentation:

- :phpmethod:`MongoDB\Client::selectDatabase()`
- :phpmethod:`MongoDB\Client::selectCollection()`
- :phpmethod:`MongoDB\Database::selectCollection()`
- :phpmethod:`MongoDB\Database::createCollection()`
- :phpmethod:`MongoDB\Database::listCollections()`
- :phpmethod:`MongoDB\Database::dropCollection()`
Loading
Loading