-
-
Notifications
You must be signed in to change notification settings - Fork 514
Expand file tree
/
Copy pathbasic-mapping.rst
More file actions
569 lines (411 loc) · 18.3 KB
/
basic-mapping.rst
File metadata and controls
569 lines (411 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
Basic Mapping
=============
This chapter explains the basic mapping of objects and properties.
Mapping of references and embedded documents will be covered in the
next chapter "Reference Mapping".
Mapping Drivers
---------------
Doctrine provides several different ways for specifying object
document mapping metadata:
- `Attributes <attributes-reference>`_
- `XML <xml-mapping>`_
- Raw PHP Code
.. note::
If you're wondering which mapping driver gives the best performance, the
answer is: None. Once the metadata of a class has been read from the source
(Attributes or XML) it is stored in an instance of the
``Doctrine\ODM\MongoDB\Mapping\ClassMetadata`` class and these instances are
stored in the metadata cache. Therefore all drivers perform equally well at
runtime.
``ClassMetadata`` instances must always be loaded through
``ClassMetadataFactory``, which restores runtime dependencies (such as the
``TypeRegistry``) after deserialization. Deserializing a ``ClassMetadata``
instance directly is not supported.
Introduction to Attributes
--------------------------
`PHP attributes <https://www.php.net/language.attributes.overview>`_
are a PHP 8+ feature that provides a native way to add metadata to classes,
methods, properties, and other language constructs. They replace doctrine
annotations by offering a standardized approach to metadata, eliminating
the need for the separate parsing library required by annotations.
In this documentation we follow the `PER Coding Style <https://www.php-fig.org/per/coding-style/#12-attributes>`_
for attributes. We use named arguments for attributes as the names of their
constructor arguments are covered by Doctrine Backward-Compatibility promise.
.. note::
Doctrine Annotations are deprecated. You can migrate to PHP Attributes
automatically `using Rector <https://getrector.com/blog/how-to-upgrade-annotations-to-attributes>`_.
Persistent classes
------------------
In order to mark a class for object-relational persistence it needs
to be designated as a document. This can be done through the
``#[Document]`` marker attribute.
.. configuration-block::
.. code-block:: php
<?php
namespace Documents;
use Doctrine\ODM\MongoDB\Mapping\Attribute as ODM;
#[ODM\Document]
class User
{
}
.. code-block:: xml
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
<document name="Documents\User">
</document>
</doctrine-mongo-mapping>
By default, the document will be persisted to a database named
doctrine and a collection with the same name as the class name. In
order to change that, you can use the ``db`` and ``collection``
option as follows:
.. configuration-block::
.. code-block:: php
<?php
namespace Documents;
use Doctrine\ODM\MongoDB\Mapping\Attribute as ODM;
#[ODM\Document(db: 'my_db', collection: 'users')]
class User
{
}
.. code-block:: xml
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
<document name="Documents\User" db="my_db" collection="users">
</document>
</doctrine-mongo-mapping>
Now instances of ``Documents\User`` will be persisted into a
collection named ``users`` in the database ``my_db``.
If you want to omit the ``db`` argument you can configure the default database
to use with the ``setDefaultDB()`` method:
.. code-block:: php
<?php
$config->setDefaultDB('my_db');
.. _doctrine_mapping_types:
Doctrine Mapping Types
----------------------
A Doctrine Mapping Type defines the mapping between a PHP type and
a MongoDB type. You can even :doc:`write your own custom mapping types <custom-mapping-types>`.
Here is a quick overview of the built-in mapping types:
- ``bin``
- ``bin_bytearray``
- ``bin_custom``
- ``bin_func``
- ``bin_md5``
- ``bin_uuid``
- ``bool``
- ``collection``
- ``custom_id``
- ``date``
- ``date_immutable``
- ``decimal128``
- ``file``
- ``float``
- ``hash``
- ``id``
- ``int``
- ``int64``
- ``key``
- ``object_id``
- ``raw``
- ``string``
- ``timestamp``
- ``uuid``
- ``vector_float32``
- ``vector_int8``
- ``vector_packed_bit``
You can read more about the available MongoDB types on `php.net <https://www.php.net/mongodb.bson>`_.
.. note::
The Doctrine mapping types are used to convert the local PHP types to the MongoDB types
when persisting so that your domain is not bound to MongoDB-specific types. For example a
DateTime instance may be converted to ``MongoDB\BSON\UTCDateTime`` when you persist your
documents, and vice versa during hydration.
Generally, the name of each built-in mapping type hints as to how the value will be converted.
This list explains some of the less obvious mapping types:
- ``bin``: ``string`` to ``MongoDB\BSON\Binary`` instance with a "generic" type (default)
- ``bin_bytearray``: ``string`` to ``MongoDB\BSON\Binary`` instance with a "byte array" type
- ``bin_custom``: ``string`` to ``MongoDB\BSON\Binary`` instance with a "custom" type
- ``bin_func``: ``string`` to ``MongoDB\BSON\Binary`` instance with a "function" type
- ``bin_md5``: ``string`` to ``MongoDB\BSON\Binary`` instance with a "md5" type
- ``bin_uuid``: ``string`` to ``MongoDB\BSON\Binary`` instance with a "uuid" type
- ``collection``: numerically indexed array to MongoDB array
- ``date``: DateTime to ``MongoDB\BSON\UTCDateTime``
- ``date_immutable``: DateTimeImmutable to ``MongoDB\BSON\UTCDateTime``
- ``decimal128``: ``string`` to ``MongoDB\BSON\Decimal128``, requires ``ext-bcmath``
- ``hash``: associative array to MongoDB object
- ``id``: ``string`` to ObjectId by default, but other formats are possible
- ``timestamp``: ``string`` to ``MongoDB\BSON\Timestamp``
- ``raw``: any type
- ``uuid``: `Symfony UID <https://symfony.com/doc/current/components/uid.html>`_ to ``MongoDB\BSON\Binary`` instance with a "uuid" type
- ``vector_float32``: list of floats to ``MongoDB\BSON\Binary`` instance with vector type "Float32"
- ``vector_int8``: list of integers to ``MongoDB\BSON\Binary`` instance with vector type "Int8"
- ``vector_packed_bit``: list of booleans to ``MongoDB\BSON\Binary`` instance with vector type "PackedBit"
.. note::
If you are using the hash type, values within the associative array are
passed to MongoDB directly, without being prepared. Only formats suitable for
the Mongo driver should be used. If your hash contains values which are not
suitable you should either use an embedded document or use formats provided
by the MongoDB driver (e.g. ``\MongoDB\BSON\UTCDateTime`` instead of ``\DateTime``).
.. note::
The vector types require the MongoDB PHP extension version 2.2.0 or higher.
.. _reference-php-mapping-types:
PHP Types Mapping
_________________
.. note::
Doctrine will skip type autoconfiguration if settings are provided explicitly.
Since version 2.4 Doctrine can determine usable defaults from property types
on document classes. Doctrine will map PHP types to ``type`` arguments as
follows:
- ``DateTime``: ``date``
- ``DateTimeImmutable``: ``date_immutable``
- ``array``: ``hash``
- ``bool``: ``bool``
- ``float``: ``float``
- ``int``: ``int``
- ``string``: ``string``
- ``Symfony\Component\Uid\Uuid``: ``uuid``
Doctrine can also autoconfigure any backed ``enum`` it encounters: ``type``
will be set to ``string`` or ``int``, depending on the enum's backing type,
and ``enumType`` to the enum's |FQCN|.
.. note::
Nullable type does not imply ``nullable`` mapping option. You need to manually
set ``nullable=true`` to have ``null`` values saved to the database.
Additionally Doctrine can determine ``collectionClass`` for ``ReferenceMany`` and
``EmbedMany`` collections from property's type.
Property Mapping
----------------
After a class has been marked as a document it can specify
mappings for its instance fields. Here we will only look at simple
fields that hold scalar values like strings, numbers, etc.
References to other objects and embedded objects are covered in the
chapter "Reference Mapping".
.. _basic_mapping_identifiers:
Identifiers
~~~~~~~~~~~
Every document class needs an identifier. You designate the field
that serves as the identifier with the ``#[Id]`` marker attribute.
Here is an example:
.. configuration-block::
.. code-block:: php
<?php
namespace Documents;
use Doctrine\ODM\MongoDB\Mapping\Attribute as ODM;
#[ODM\Document]
class User
{
#[ODM\Id]
public string $id;
}
.. code-block:: xml
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
<document name="Documents\User">
<id />
</document>
</doctrine-mongo-mapping>
You can configure custom ID strategies if you don't want to use the default
object ID. The available strategies are:
- ``AUTO`` - Automatically generates an ObjectId or Symfony UUID depending on the identifier type.
- ``ALNUM`` - Generates an alpha-numeric string (based on an incrementing value).
- ``CUSTOM`` - Defers generation to an implementation of ``IdGenerator`` specified in the ``class`` option.
- ``INCREMENT`` - Uses another collection to auto increment an integer identifier.
- ``UUID`` - Generates a UUID identifier (deprecated).
- ``NONE`` - Do not generate any identifier. ID must be manually set.
When using the ``AUTO`` strategy in combination with a UUID identifier, the generator can create UUIDs of type 1, type 4,
and type 7 automatically. For all other UUID types, assign the identifier manually in combination with the ``NONE``
strategy.
.. note::
The ``UUID`` generator is deprecated, as it stores UUIDs as strings. It is recommended to use the ``AUTO`` strategy
with a ``uuid`` type identifier field instead. If you need to keep generating string UUIDs, you can use the
``CUSTOM`` strategy with your own generator.
Here is an example how to manually set a string identifier for your documents:
.. configuration-block::
.. code-block:: php
<?php
namespace Documents;
use Doctrine\ODM\MongoDB\Mapping\Attribute as ODM;
#[ODM\Document]
class MyPersistentClass
{
#[ODM\Id(strategy: 'NONE', type: 'string')]
public string $id;
//...
}
.. code-block:: xml
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
<document name="MyPersistentClass">
<id strategy="NONE" type="string" />
</document>
</doctrine-mongo-mapping>
When using the ``NONE`` strategy you will have to explicitly set an id before persisting the document:
.. code-block:: php
<?php
//...
$document = new MyPersistentClass();
$document->setId('my_unique_identifier');
$dm->persist($document);
$dm->flush();
Now you can retrieve the document later:
.. code-block:: php
<?php
//...
$document = $dm->find(MyPersistentClass::class, 'my_unique_identifier');
You can define your own ID generator by implementing the
``Doctrine\ODM\MongoDB\Id\IdGenerator`` interface:
.. code-block:: php
<?php
namespace Vendor\Specific;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Id\IdGenerator;
class Generator implements IdGenerator
{
public function generate(DocumentManager $dm, object $document)
{
// Your own logic here
return 'my_generated_id';
}
}
Then specify the ``class`` option for the ``CUSTOM`` strategy:
.. configuration-block::
.. code-block:: php
<?php
#[Document]
class MyPersistentClass
{
#[Id(strategy: 'CUSTOM', type: 'string', options: ['class' => \Vendor\Specific\Generator::class])]
private string $id;
public function setId(string $id): void
{
$this->id = $id;
}
//...
}
.. code-block:: xml
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
<document name="MyPersistentClass">
<id strategy="CUSTOM" type="string">
<generator-option name="class" value="Vendor\Specific\Generator" />
</id>
</document>
</doctrine-mongo-mapping>
Fields
~~~~~~
To mark a property to be persisted in the document, add the ``#[Field]``
attribute. The name and the type of the field are inferred from the property
name and type.
Example:
.. configuration-block::
.. code-block:: php
<?php
namespace Documents;
use Doctrine\ODM\MongoDB\Mapping\Attribute as ODM;
#[ODM\Document]
class User
{
// ...
#[ODM\Field]
public string $username;
}
.. code-block:: xml
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
<document name="Documents\User">
<id />
<field field-name="username" type="string" />
</document>
</doctrine-mongo-mapping>
In that example we mapped the property ``id`` to the field ``id``
using the mapping type ``id`` and the property ``name`` is mapped
to the field ``name`` with the default mapping type ``string``.
To specify a different name for the field, you can use the ``name`` argument
of the Field attribute as follows:
.. configuration-block::
.. code-block:: php
<?php
class User
{
#[Field(name: 'db_name')]
public string $name;
}
.. code-block:: xml
<field field-name="name" name="db_name" />
Date Fields
~~~~~~~~~~~
MongoDB has a specific database type to store date and time values. You should never
use a string to store a date. To define a date field, use the property types
``DateTime`` or ``DateTimeImmutable`` so that Doctrine maps it to a BSON date.
The ``date`` and ``date_immutable`` mapping types can be used explicitly;
they are required only if the property type is ``DateTimeInterface`` or not set.
.. configuration-block::
.. code-block:: php
<?php
class User
{
#[Field]
public \DateTimeImmutable $immutableDateTime;
#[Field]
public \DateTime $mutableDateTime;
#[Field(type: 'date_immutable')]
public \DateTimeInterface $datetime;
}
.. code-block:: xml
<field field-name="immutableDateTime" type="date_immutable" />
<field field-name="mutableDateTime" name="date" />
<field field-name="datetime" name="date_immutable" />
.. note::
Prefer using ``DateTimeImmutable`` over ``DateTime`` to avoid issues with
mutable objects. If you need to modify a date, create a new instance
and assign it to the property.
Multiple Document Types in a Collection
---------------------------------------
You can easily store multiple types of documents in a single collection. This
requires specifying the same collection name, ``discriminatorField``, and
(optionally) ``discriminatorMap`` mapping options for each class that will share
the collection. Here is an example:
.. code-block:: php
<?php
#[Document(collection: 'my_documents')]
#[DiscriminatorField('type')]
#[DiscriminatorMap(['article' => Article::class, 'album' => Album::class])]
class Article
{
// ...
}
#[Document(collection: 'my_documents')]
#[DiscriminatorField('type')]
#[DiscriminatorMap(['article' => Article::class, 'album' => Album::class])]
class Album
{
// ...
}
All instances of ``Article`` and ``Album`` will be stored in the
``my_documents`` collection. You can query for the documents of a particular
class just like you normally would and the results will automatically be limited
based on the discriminator value for that class.
If you wish to query for multiple types of documents from the collection, you
may pass an array of document class names when creating a query builder:
.. code-block:: php
<?php
$query = $dm->createQuery([Article::class, Album::class]);
$documents = $query->execute();
The above will return a cursor that will allow you to iterate over all
``Article`` and ``Album`` documents in the collections.
.. |FQCN| raw:: html
<abbr title="Fully-Qualified Class Name">FQCN</abbr>