You are browsing a version that is no longer maintained. |
Annotations Reference
In this chapter a reference of every Doctrine 2 ODM Annotation is given with short explanations on their context and usage.
@AlsoLoad
Specify one or more MongoDB fields to use for loading data if the original field does not exist.
The $fullName
property will be loaded from fullName
if it exists, but
fall back to name
if it does not exist. If multiple fall back fields are
specified, ODM will consider them in order until the first is found.
Additionally, @AlsoLoad may annotate a method with one or more field names. Before normal hydration, the field(s) will be considered in order and the method will be invoked with the first value found as its single argument.
For additional information on using @AlsoLoad, see Migrations.
@Bin
Alias of @Field, with "type" attribute set to "bin". Converts value to
MongoBinData with MongoBinData::GENERIC
sub-type.
This annotation is deprecated and will be removed in ODM 2.0. Please use the @Field annotation with type "bin". |
@BinCustom
Alias of @Field, with "type" attribute set to "bin_custom". Converts
value to MongoBinData with MongoBinData::CUSTOM
sub-type.
This annotation is deprecated and will be removed in ODM 2.0. Please use the @Field annotation with type "bin_custom". |
@BinFunc
Alias of @Field, with "type" attribute set to "bin_func". Converts value to
MongoBinData with MongoBinData::FUNC
sub-type.
This annotation is deprecated and will be removed in ODM 2.0. Please use the @Field annotation with type "bin_func". |
@BinMD5
Alias of @Field, with "type" attribute set to "bin_md5". Converts value to
MongoBinData with MongoBinData::MD5
sub-type.
This annotation is deprecated and will be removed in ODM 2.0. Please use the @Field annotation with type "bin_md5". |
@BinUUID
Alias of @Field, with "type" attribute set to "bin_uuid". Converts value to
MongoBinData with MongoBinData::UUID
sub-type.
Per the BSON specification, this sub-type is deprecated in favor of the RFC 4122 UUID sub-type. Consider using @BinUUIDRFC4122 instead. |
@BinUUIDRFC4122
Alias of @Field, with "type" attribute set to "bin_uuid_rfc4122". Converts
value to MongoBinData with MongoBinData::UUID_RFC4122
sub-type.
RFC 4122 UUIDs must be 16 bytes. The PHP driver will throw an exception if the binary data's size is invalid. |
This annotation is deprecated and will be removed in ODM 2.0. Please use the @Field annotation with type "bin_uuid_rfc4122". |
@Bool
Alias of @Field, with "type" attribute set to "bool". Internally it uses exactly same logic as @Boolean annotation and "boolean" type.
This annotation is deprecated because it uses a keyword that was reserved in PHP 7. It will be removed in ODM 2.0. Please use the @Field annotation with type "bool". |
@Boolean
Alias of @Field, with "type" attribute set to "boolean".
This annotation is deprecated and will be removed in ODM 2.0. Please use the @Field annotation with type "bool". |
@ChangeTrackingPolicy
This annotation is used to change the change tracking policy for a document:
For a list of available policies, read the section on change tracking policies.
@Collection
Alias of @Field, with "type" attribute set to "collection". Stores and retrieves the value as a numerically indexed array.
This annotation is deprecated and will be removed in ODM 2.0. Please use the @Field annotation with type "collection". |
@Date
Alias of @Field, with "type" attribute set to "date". Values of any type (e.g. integer, string, DateTime) will be converted to MongoDate for storage in MongoDB. The property will be a DateTime when loaded from the database.
This annotation is deprecated and will be removed in ODM 2.0. Please use the @Field annotation with type "date". |
@DefaultDiscriminatorValue
This annotation can be used when using @DiscriminatorField. It will be used as a fallback value if a document has no discriminator field set. This must correspond to a value from the configured discriminator map.
@DiscriminatorField
This annotation is required for the top-most class in a single collection inheritance hierarchy. It takes a string as its only argument, which specifies the database field to store a class name or key (if a discriminator map is used). ODM uses this field during hydration to select the instantiation class.
For backwards compatibility, the discriminator field may also be specified
via either the |
@DiscriminatorMap
This annotation is required for the top-most class in a single collection inheritance hierarchy. It takes an array as its only argument, which maps keys to class names. The class names may be fully qualified or relative to the current namespace. When a document is persisted to the database, its class name key will be stored in the discriminator field instead of the FQCN.
@Distance
This annotation can be used in combination with geospatial indexes and the geoNear() query method to populate the property with the calculated distance value.
1 <?php
/**
* @Document
* @Index(keys={"coordinates"="2d"})
*/
class Place
{
/** @Id */
public $id;
/** @EmbedOne(targetDocument="Coordinates") */
public $coordinates;
/** @Distance */
public $distance;
}
/** @EmbeddedDocument */
class Coordinates
{
/** @Field(type="float") */
public $latitude;
/** @Field(type="float") */
public $longitude;
}
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
Now you can run a geoNear command and access the computed distance. The following example would return the distance of the city nearest the query coordinates:
@Document
Required annotation to mark a PHP class as a document, whose peristence will be managed by ODM.
Optional attributes:
- db - By default, the document manager will use the MongoDB database defined in the configuration, but this option may be used to override the database for a particular document class.
- collection - By default, the collection name is derived from the document's class name, but this option may be used to override that behavior.
- repositoryClass - Specifies a custom repository class to use.
- indexes - Specifies an array of indexes for this document.
- requireIndexes - Specifies whether or not queries for this document should require indexes by default. This may also be specified per query.
- writeConcern - Specifies the write concern for this document that overwrites
the default write concern specified in the configuration. It does not overwrite
a write concern given as option to the
flush
method when committing your documents.
@EmbedMany
This annotation is similar to @EmbedOne, but instead of embedding one document, it embeds a collection of documents.
Optional attributes:
- targetDocument - A FQCN of the target document.
- discriminatorField - The database field name to store the discriminator value within the embedded document.
- discriminatorMap - Map of discriminator values to class names.
- defaultDiscriminatorValue - A default value for discriminatorField if no value has been set in the embedded document.
- strategy - The strategy used to persist changes to the collection. Possible
values are
addToSet
,pushAll
,set
, andsetArray
.pushAll
is the default. See Storage Strategies for more information. - collectionClass - A FQCN of class that implements
Collection
interface and is used to hold documents. Doctrine'sArrayCollection
is used by default.
Depending on the embedded document's class, a value of user
or author
will be stored in the type
field and used to reconstruct the proper class
during hydration. The type
field need not be mapped on the embedded
document classes.
@EmbedOne
The @EmbedOne annotation works similarly to @ReferenceOne, except that that document will be embedded within the parent document. Consider the following excerpt from the MongoDB documentation:
The key question in MongoDB schema design is "does this object merit its own collection, or rather should it be embedded within objects in other collections?" In relational databases, each sub-item of interest typically becomes a separate table (unless you are denormalizing for performance). In MongoDB, this is not recommended – embedding objects is much more efficient. Data is then collocated on disk; client-server turnarounds to the database are eliminated. So in general, the question to ask is, "why would I not want to embed this object?"
Optional attributes:
- targetDocument - A FQCN of the target document.
- discriminatorField - The database field name to store the discriminator value within the embedded document.
- discriminatorMap - Map of discriminator values to class names.
- defaultDiscriminatorValue - A default value for discriminatorField if no value has been set in the embedded document.
Depending on the embedded document's class, a value of user
or author
will be stored in the type
field and used to reconstruct the proper class
during hydration. The type
field need not be mapped on the embedded
document classes.
@EmbeddedDocument
Marks the document as embeddable. This annotation is required for any documents to be stored within an @EmbedOne or @EmbedMany relationship.
1 <?php
/** @EmbeddedDocument */
class Money
{
/** @Field(type="float") */
private $amount;
public function __construct($amount)
{
$this->amount = (float) $amount;
}
//...
}
/** @Document(db="finance", collection="wallets") */
class Wallet
{
/** @EmbedOne(targetDocument="Money") */
private $money;
public function setMoney(Money $money)
{
$this->money = $money;
}
//...
}
//...
$wallet = new Wallet();
$wallet->setMoney(new Money(34.39));
$dm->persist($wallet);
$dm->flush();
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
Unlike normal documents, embedded documents cannot specify their own database or collection. That said, a single embedded document class may be used with multiple document classes, and even other embedded documents!
Optional attributes:
- indexes - Specifies an array of indexes for this embedded document, to be included in the schemas of any embedding documents.
@Field
Marks an annotated instance variable for persistence. Values for this field will be saved to and loaded from the document store as part of the document class' lifecycle.
Optional attributes:
- type - Name of the ODM type, which will determine the value's representation in PHP and BSON (i.e. MongoDB). See Doctrine Mapping Types for a list of types. Defaults to "string".
- name - By default, the property name is used for the field name in MongoDB; however, this option may be used to specify a database field name.
- nullable - By default, ODM will
$unset
fields in MongoDB if the PHP value is null. Specify true for this option to force ODM to store a null value in the database instead of unsetting the field.
Examples:
@File
Marks an annotated instance variable as a file. Additionally, this instructs ODM to store the entire document in GridFS. Only a single field in a document may be mapped as a file.
The instance variable will be an Doctrine\MongoDB\GridFSFile
object, which
is a wrapper class for MongoGridFSFile and facilitates access to the file
data in GridFS. If the variable is a file path string when the document is first
persisted, ODM will convert it to GridFSFile object automatically.
Additional fields can be mapped in GridFS documents like any other, but metadata
fields set by the driver (e.g. length
) should be mapped with @NotSaved so
as not to inadvertently overwrite them. Some metadata fields, such as
filename
may be modified and do not require @NotSaved. In the following
example, we also add a custom field to refer to the corresponding User document
that created the file.
1 <?php
/** @Field(type="string") */
private $filename;
/** @NotSaved(type="int") */
private $length;
/** @NotSaved(type="string") */
private $md5;
/** @NotSaved(type="date") */
private $uploadDate;
/** @ReferenceOne(targetDocument="Documents\User") */
private $uploadedBy;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Float
Alias of @Field, with "type" attribute set to "float".
This annotation is deprecated because it uses a keyword that was reserved in PHP 7. It will be removed in ODM 2.0. Please use the @Field annotation with type "float". |
@HasLifecycleCallbacks
This annotation must be set on the document class to instruct Doctrine to check for lifecycle callback annotations on public methods. Using @PreFlush, @PreLoad, @PostLoad, @PrePersist, @PostPersist, @PreRemove, @PostRemove, @PreUpdate, or @PostUpdate on methods without this annotation will cause Doctrine to ignore the callbacks.
@Hash
Alias of @Field, with "type" attribute set to "hash". Stores and retrieves the value as an associative array.
This annotation is deprecated and will be removed in ODM 2.0. Please use the @Field annotation with type "hash". |
@Id
The annotated instance variable will be marked as the document identifier. The default behavior is to store a MongoId instance, but you may customize this via the strategy attribute.
@Increment
The increment type is just like an integer field, except that it will be updated
using the $inc
operator instead of $set
:
Now, update a Package instance like so:
The query sent to Mongo would resemble the following:
1 { "$inc": { "downloads": 1 } }
The field will be incremented by the difference between the new and old values. This is useful if many requests are attempting to update the field concurrently.
This annotation is deprecated and will be removed in ODM 2.0. Please use the @Field annotation with type "int" or "float" and use the "increment" strategy. |
@Index
This annotation is used inside of the class-level @Document or @EmbeddedDocument annotations to specify indexes to be created on the collection (or embedding document's collection in the case of @EmbeddedDocument). It may also be used at the property-level to define single-field indexes.
Optional attributes:
- keys - Mapping of indexed fields to their ordering or index type. ODM will
allow "asc" and "desc" to be used in place of
1
and-1
, respectively. Special index types (e.g. "2dsphere") should be specified as strings. This is required when @Index is used at the class level. - options - Options for creating the index
The keys
and options
attributes correspond to the arguments for
MongoCollection::createIndex().
ODM allows mapped field names (i.e. PHP property names) to be used when defining
keys
.
If you are creating a single-field index, you can simply specify an @Index or @UniqueIndex on a mapped property:
@Indexes
This annotation may be used at the class level to specify an array of @Index
annotations. It is functionally equivalent to using the indexes
option for
the @Document or @EmbeddedDocument annotations.
@InheritanceType
This annotation must appear on the top-most class in an
inheritance hierarchy. SINGLE_COLLECTION
and
COLLECTION_PER_CLASS
are currently supported.
Examples:
1 <?php
/**
* @Document
* @InheritanceType("COLLECTION_PER_CLASS")
*/
class Person
{
// ...
}
/**
* @Document
* @InheritanceType("SINGLE_COLLECTION")
* @DiscriminatorField("type")
* @DiscriminatorMap({"person"="Person", "employee"="Employee"})
*/
class Person
{
// ...
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Int
Alias of @Field, with "type" attribute set to "int".
This annotation is deprecated because it uses a keyword that was reserved in PHP 7. It will be removed in ODM 2.0. Please use the @Field annotation with type "int". |
@Integer
Alias of @Field, with "type" attribute set to "integer". Internally it uses exactly same logic as @Int annotation and "int" type.
This annotation is deprecated and will be removed in ODM 2.0. Please use the @Field annotation with type "int". |
@Key
Alias of @Field, with "type" attribute set to "key". The value will be converted to MongoMaxKey or MongoMinKey if it is true or false, respectively.
The BSON MaxKey and MinKey types are internally used by MongoDB for indexing and sharding. There is generally no reason to use these in an application. |
This annotation is deprecated and will be removed in ODM 2.0. Please use the @Field annotation with type "key". |
@MappedSuperclass
The annotation is used to specify classes that are parents of document classes and should not be managed directly. See inheritance mapping for additional information.
@NotSaved
The annotation is used to specify properties that are loaded if they exist in MongoDB; however, ODM will not save the property value back to the database.
@PostLoad
Marks a method on the document class to be called on the postLoad
event. The
@HasLifecycleCallbacks annotation must be present on the same class for the
method to be registered.
See Lifecycle Events for more information.
@PostPersist
Marks a method on the document class to be called on the postPersist
event.
The @HasLifecycleCallbacks annotation must be present on the same class for
the method to be registered.
See Lifecycle Events for more information.
@PostRemove
Marks a method on the document class to be called on the postRemove
event.
The @HasLifecycleCallbacks annotation must be present on the same class for
the method to be registered.
See Lifecycle Events for more information.
@PostUpdate
Marks a method on the document class to be called on the postUpdate
event.
The @HasLifecycleCallbacks annotation must be present on the same class for
the method to be registered.
See Lifecycle Events for more information.
@PreFlush
Marks a method on the document class to be called on the preFlush
event. The
@HasLifecycleCallbacks annotation must be present on the same class for the
method to be registered.
See Lifecycle Events for more information.
@PreLoad
Marks a method on the document class to be called on the preLoad
event. The
@HasLifecycleCallbacks annotation must be present on the same class for the
method to be registered.
See Lifecycle Events for more information.
@PrePersist
Marks a method on the document class to be called on the prePersist
event.
The @HasLifecycleCallbacks annotation must be present on the same class for
the method to be registered.
See Lifecycle Events for more information.
@PreRemove
Marks a method on the document class to be called on the preRemove
event.
The @HasLifecycleCallbacks annotation must be present on the same class for
the method to be registered.
See Lifecycle Events for more information.
@PreUpdate
Marks a method on the document class to be called on the preUpdate
event.
The @HasLifecycleCallbacks annotation must be present on the same class for
the method to be registered.
See Lifecycle Events for more information.
@ReferenceMany
Defines that the annotated instance variable holds a collection of referenced documents.
Optional attributes:
- targetDocument - A FQCN of the target document.
- simple - deprecated (use
storeAs: id
) - storeAs - Indicates how to store the reference.
id
usesMongoId
,dbRef
uses a DBRef without$db
value anddbRefWithDb
stores a full DBRef ($ref
,$id
, and$db
). Note thatid
references are not compatible with the discriminators. - cascade - Cascade Option
- discriminatorField - The field name to store the discriminator value within the DBRef object.
- discriminatorMap - Map of discriminator values to class names.
- defaultDiscriminatorValue - A default value for discriminatorField if no value has been set in the embedded document.
- inversedBy - The field name of the inverse side. Only allowed on owning side.
- mappedBy - The field name of the owning side. Only allowed on the inverse side.
- repositoryMethod - The name of the repository method to call to populate this reference.
- sort - The default sort for the query that loads the reference.
- criteria - Array of default criteria for the query that loads the reference.
- limit - Limit for the query that loads the reference.
- skip - Skip for the query that loads the reference.
- strategy - The strategy used to persist changes to the collection. Possible
values are
addToSet
,pushAll
,set
, andsetArray
.pushAll
is the default. See Storage Strategies for more information. - collectionClass - A FQCN of class that implements
Collection
interface and is used to hold documents. Doctrine'sArrayCollection
is used by default
1 <?php
/**
* @ReferenceMany(
* strategy="set",
* targetDocument="Documents\Item",
* cascade="all",
* sort={"sort_field": "asc"}
* discriminatorField="type",
* discriminatorMap={
* "book"="Documents\BookItem",
* "song"="Documents\SongItem"
* },
* defaultDiscriminatorValue="book"
* )
*/
private $cart;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@ReferenceOne
Defines an instance variable holds a related document instance.
Optional attributes:
- targetDocument - A FQCN of the target document.
- simple - deprecated (use
storeAs: id
) - storeAs - Indicates how to store the reference.
id
usesMongoId
,dbRef
uses a DBRef without$db
value anddbRefWithDb
stores a full DBRef ($ref
,$id
, and$db
). Note thatid
references are not compatible with the discriminators. - cascade - Cascade Option
- discriminatorField - The field name to store the discriminator value within the DBRef object.
- discriminatorMap - Map of discriminator values to class names.
- defaultDiscriminatorValue - A default value for discriminatorField if no value has been set in the embedded document.
- inversedBy - The field name of the inverse side. Only allowed on owning side.
- mappedBy - The field name of the owning side. Only allowed on the inverse side.
- repositoryMethod - The name of the repository method to call to populate this reference.
- sort - The default sort for the query that loads the reference.
- criteria - Array of default criteria for the query that loads the reference.
- limit - Limit for the query that loads the reference.
- skip - Skip for the query that loads the reference.
@ShardKey
This annotation may be used at the class level to specify a shard key to be used for sharding the document collection.
@String
Alias of @Field, with "type" attribute set to "string".
This annotation is deprecated because it uses a keyword that was reserved in PHP 7. It will be removed in ODM 2.0. Please use the @Field annotation with type "string". |
@Timestamp
Alias of @Field, with "type" attribute set to "timestamp". The value will be converted to MongoTimestamp for storage in MongoDB.
The BSON timestamp type is an internal type used for MongoDB's replication and sharding. If you need to store dates in your application, you should use the "date" type instead. |
This annotation is deprecated and will be removed in ODM 2.0. Please use the @Field annotation with type "timestamp". |
@Version
The annotated instance variable will be used to store version information, which is used for pessimistic and optimistic locking. This is only compatible with integer and date field types, and cannot be combined with @Id.
By default, Doctrine ODM processes updates embed-many and reference-many collections in separate write operations, which do not bump the document version. Users employing document versioning are encouraged to use the atomicSet or atomicSetArray strategies for such collections, which will ensure that collections are updated in the same write operation as the versioned document.