Skip to content

Commit bde5e59

Browse files
authored
DOCSP-41963: Databases and collections (#136)
* DOCSP-41963: Databases and collections * edits * phpmethod * code fix * MW feedback * fix * MW feedback 2 * JM feedback * JM feedback 2
1 parent a772b6a commit bde5e59

File tree

3 files changed

+428
-0
lines changed

3 files changed

+428
-0
lines changed

source/databases-collections.txt

Lines changed: 322 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,322 @@
1+
.. _php-databases-collections:
2+
3+
=========================
4+
Databases and Collections
5+
=========================
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
.. facet::
14+
:name: genre
15+
:values: reference
16+
17+
.. meta::
18+
:keywords: table, row, organize, storage, code example
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to use MongoDB databases and
24+
collections with the {+php-library+}.
25+
26+
MongoDB organizes data into a hierarchy of the following levels:
27+
28+
- **Databases**: Top-level data structures in a MongoDB deployment that store collections.
29+
- **Collections**: Groups of MongoDB documents. They are analogous to tables in relational databases.
30+
- **Documents**: Units that store literal data such as string, numbers, dates, and other embedded documents.
31+
For more information about document field types and structure, see the
32+
:manual:`Documents </core/document/>` guide in the {+mdb-server+} manual.
33+
34+
Access a Database
35+
-----------------
36+
37+
Access a database by passing the database name to the ``MongoDB\Client::selectDatabase()``
38+
method.
39+
40+
The following example accesses a database named ``test_database``:
41+
42+
.. literalinclude:: /includes/databases-collections/databases-collections.php
43+
:language: php
44+
:dedent:
45+
:start-after: start-access-database
46+
:end-before: end-access-database
47+
48+
Alternatively, you can implicitly call the ``MongoDB\Client::__get()`` magic method on
49+
a client object. This method allows you to select a database by using the syntax for
50+
accessing a class property. The following example uses this shorthand syntax to access
51+
the ``test_database`` database:
52+
53+
.. literalinclude:: /includes/databases-collections/databases-collections.php
54+
:language: php
55+
:dedent:
56+
:start-after: start-access-database-short
57+
:end-before: end-access-database-short
58+
59+
.. tip::
60+
61+
To learn more about ``__get()`` and PHP magic methods, see the following resources:
62+
63+
- :phpmethod:`MongoDB\Client::__get()` in the API documentation
64+
- `Magic Methods <{+php-manual+}/language.oop5.magic.php>`__ in the PHP manual
65+
66+
.. _php-db-coll-access-collection:
67+
68+
Access a Collection
69+
-------------------
70+
71+
Access a collection by using either of the following methods:
72+
73+
- ``MongoDB\Client::selectCollection()``: Pass the database and collection names as
74+
parameters
75+
- ``MongoDB\Database::selectCollection()``: Pass the collection name as a parameter
76+
77+
The following example accesses a collection named ``test_collection`` by using the
78+
``MongoDB\Database::selectCollection()`` method:
79+
80+
.. literalinclude:: /includes/databases-collections/databases-collections.php
81+
:language: php
82+
:dedent:
83+
:start-after: start-access-collection
84+
:end-before: end-access-collection
85+
86+
.. tip::
87+
88+
If the provided collection name does not already exist in the database,
89+
MongoDB implicitly creates the collection when you first insert data
90+
into it.
91+
92+
Alternatively, you can implicitly call the ``MongoDB\Database::__get()`` magic method on
93+
a database object. This method allows you to select a collection by using the syntax for
94+
accessing a class property. The following example uses this shorthand syntax to access
95+
the ``test_collection`` collection:
96+
97+
.. literalinclude:: /includes/databases-collections/databases-collections.php
98+
:language: php
99+
:dedent:
100+
:start-after: start-access-collection-short
101+
:end-before: end-access-collection-short
102+
103+
To learn more, see the :phpmethod:`MongoDB\Database::__get()`
104+
API documentation.
105+
106+
.. _php-db-coll-create-collection:
107+
108+
Create a Collection
109+
-------------------
110+
111+
Pass a collection name to the ``MongoDB\Database::createCollection()`` method to
112+
explicitly create a collection in a MongoDB database.
113+
114+
The following example creates a collection named ``example_collection``:
115+
116+
.. literalinclude:: /includes/databases-collections/databases-collections.php
117+
:language: php
118+
:dedent:
119+
:start-after: start-create-collection
120+
:end-before: end-create-collection
121+
122+
You can specify collection options, such as maximum size and document
123+
validation rules, by passing them as an array to the ``createCollection()`` method.
124+
For a full list of optional parameters, see the `API documentation
125+
<{+api+}/method/MongoDBDatabase-createCollection/#parameters>`__.
126+
127+
Get a List of Collections
128+
-------------------------
129+
130+
You can query for a list of collections in a database by calling the
131+
``MongoDB\Database::listCollections()`` method. The method returns a
132+
cursor containing all collections in the database and their associated metadata.
133+
134+
The following example calls the ``listCollections()`` method and iterates over
135+
the returned iterator to print the collections from the :ref:`php-db-coll-access-collection`
136+
and :ref:`php-db-coll-create-collection` examples:
137+
138+
.. io-code-block::
139+
:copyable:
140+
141+
.. input:: /includes/databases-collections/databases-collections.php
142+
:language: php
143+
:start-after: start-find-collections
144+
:end-before: end-find-collections
145+
:dedent:
146+
147+
.. output::
148+
:language: console
149+
:visible: false
150+
151+
MongoDB\Model\CollectionInfo Object
152+
(
153+
[name] => example_collection
154+
[type] => collection
155+
...
156+
)
157+
MongoDB\Model\CollectionInfo Object
158+
(
159+
[name] => test_collection
160+
[type] => collection
161+
...
162+
)
163+
164+
Delete a Collection
165+
-------------------
166+
167+
You can delete a collection from the database by using the ``MongoDB\Database::dropCollection()``
168+
method.
169+
170+
The following example deletes the ``test_collection`` collection:
171+
172+
.. literalinclude:: /includes/databases-collections/databases-collections.php
173+
:language: php
174+
:dedent:
175+
:start-after: start-drop-collection
176+
:end-before: end-drop-collection
177+
178+
.. warning:: Dropping a Collection Deletes All Data in the Collection
179+
180+
Dropping a collection from your database permanently deletes all
181+
documents and all indexes within that collection.
182+
183+
Drop a collection only if you no longer need the data in it.
184+
185+
.. _php-config-read-write:
186+
187+
Configure Read and Write Operations
188+
-----------------------------------
189+
190+
You can control how the library routes read operations by setting a **read preference**.
191+
You can also control options for how the library waits for acknowledgment of
192+
read and write operations on a replica set by setting a **read concern** and a
193+
**write concern**.
194+
195+
By default, databases inherit read and write settings from the ``MongoDB\Client``
196+
instance. Collections inherit these settings from the ``MongoDB\Client`` or
197+
``MongoDB\Database`` instance on which the ``selectCollection()`` method is called.
198+
You can change these settings by passing an options array to the
199+
``MongoDB\Client::selectDatabase()``, ``MongoDB\Client::selectCollection()``, or
200+
``MongoDB\Database::selectCollection()`` methods.
201+
202+
To change the read preference, read concern, and write concern of your database
203+
or collection, set the following options in the array parameter:
204+
205+
- ``readPreference``: Sets the read preference. For a list of available read
206+
preferences, see :php:`MongoDB\Driver\ReadPreference <mongodb-driver-readpreference>`
207+
in the extension API documentation.
208+
- ``readConcern``: Sets the read concern. For a list of available read
209+
concerns, see :php:`MongoDB\Driver\ReadConcern <mongodb-driver-readconcern>`
210+
in the extension API documentation.
211+
- ``writeConcern``: Sets the write concern. For a list of available write
212+
concerns, see :php:`MongoDB\Driver\WriteConcern <mongodb-driver-writeconcern>`
213+
in the extension API documentation.
214+
215+
.. tip::
216+
217+
To learn more about read preferences and read and write concerns, see the
218+
following guides in the MongoDB Server manual:
219+
220+
- :manual:`Read Preference </core/read-preference/>`
221+
- :manual:`Read Concern </reference/read-concern/>`
222+
- :manual:`Write Concern </reference/write-concern/>`
223+
224+
Database Configuration Example
225+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
226+
227+
The following example shows how to set the read preference, read concern, and
228+
write concern of a database called ``test_database`` by passing an options
229+
array to ``selectDatabase()``:
230+
231+
.. literalinclude:: /includes/databases-collections/databases-collections.php
232+
:language: php
233+
:dedent:
234+
:start-after: start-database-settings
235+
:end-before: end-database-settings
236+
237+
Collection Configuration Example
238+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
239+
240+
The following example shows how to set the read preference, read concern, and
241+
write concern of a collection called ``test_collection`` by passing an options
242+
array to ``selectCollection()``:
243+
244+
.. literalinclude:: /includes/databases-collections/databases-collections.php
245+
:language: php
246+
:dedent:
247+
:start-after: start-collection-settings
248+
:end-before: end-collection-settings
249+
250+
Advanced Read Configurations
251+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
252+
253+
Tag Sets
254+
````````
255+
256+
In {+mdb-server+}, you can apply key-value :manual:`tags
257+
</core/read-preference-tags/>` to replica-set
258+
members according to any criteria you choose. You can then use
259+
those tags to target one or more members for a read operation.
260+
261+
By default, the {+php-library+} ignores tags when choosing a member
262+
to read from. To instruct the {+php-library+} to prefer certain tags,
263+
pass them as a parameter to your ``MongoDB\Driver\ReadPreference`` class
264+
constructor. Then, set the ``MongoDB\Driver\ReadPreference`` object as
265+
the value of the ``readPreference`` database option.
266+
267+
This code example sets the ``readPreference`` option to a tag set
268+
that instructs ``test_database`` to prefer reads from secondary replica set
269+
members in the following order:
270+
271+
1. Members from the New York data center (``['dc' => 'ny']``)
272+
#. Members from the San Francisco data center (``['dc' => 'sf']``)
273+
#. Any secondary members (``[]``)
274+
275+
.. literalinclude:: /includes/databases-collections/databases-collections.php
276+
:language: php
277+
:dedent:
278+
:start-after: start-tag-set
279+
:end-before: end-tag-set
280+
281+
Local Threshold
282+
```````````````
283+
284+
If multiple replica-set members match the read preference and tag sets you specify,
285+
the {+php-library+} reads from the nearest replica-set members, chosen according to
286+
their ping time.
287+
288+
By default, the library uses only members whose ping times are within 15 milliseconds
289+
of the nearest member for queries. To distribute reads between members with
290+
higher latencies, pass an options array to the ``MongoDB\Client`` constructor that
291+
sets the ``localThresholdMS`` option.
292+
293+
The following example specifies a local threshold of 35 milliseconds:
294+
295+
.. literalinclude:: /includes/databases-collections/databases-collections.php
296+
:language: php
297+
:dedent:
298+
:start-after: start-local-threshold
299+
:end-before: end-local-threshold
300+
301+
In the preceding example, the {+php-library+} distributes reads among matching members
302+
within 35 milliseconds of the closest member's ping time.
303+
304+
.. note::
305+
306+
The {+php-library+} ignores the value of ``localThresholdMS`` when communicating with a
307+
replica set through a ``mongos`` instance. In this case, use the
308+
:manual:`localThreshold </reference/program/mongos/#std-option-mongos.--localThreshold>`
309+
command-line option.
310+
311+
API Documentation
312+
-----------------
313+
314+
To learn more about any of the methods or types discussed in this
315+
guide, see the following API documentation:
316+
317+
- :phpmethod:`MongoDB\Client::selectDatabase()`
318+
- :phpmethod:`MongoDB\Client::selectCollection()`
319+
- :phpmethod:`MongoDB\Database::selectCollection()`
320+
- :phpmethod:`MongoDB\Database::createCollection()`
321+
- :phpmethod:`MongoDB\Database::listCollections()`
322+
- :phpmethod:`MongoDB\Database::dropCollection()`

0 commit comments

Comments
 (0)