Configuration
Sample Configuration
# config/packages/doctrine_mongodb.yamldoctrine_mongodb: connections: default: server: mongodb://localhost:27017 options: {} default_database: hello_%kernel.environment% document_managers: default: mappings: App: is_bundle: false dir: '%kernel.project_dir%/src/Document' prefix: 'App\Document' alias: App metadata_cache_driver: array # array, service, apcu, memcached, redis
}
|
If each environment requires a different MongoDB connection URI, you can define it as an environment variable and reference it in the bundle's config:
|
If you wish to use memcached to cache your metadata, you need to configure the
Memcached instance; for example, you can do the following:
# app/config/config.ymldoctrine_mongodb: default_database: hello_%kernel.environment% connections: default: server: mongodb://localhost:27017 options: {} document_managers: default: mappings: App: ~ metadata_cache_driver: type: memcached class: Symfony\Component\Cache\Adapter\MemcachedAdapter host: localhost port: 11211 instance_class: Memcached
Mapping Configuration
Explicit definition of all the mapped documents is the only necessary configuration for the ODM and there are several configuration options that you can control. The following configuration options exist for a mapping:
typeOne ofattribute,xml,phporstaticphp. This specifies which type of metadata type your mapping uses.dirPath to the mapping or document files (depending on the driver). If this path is relative it is assumed to be relative to the bundle root. This only works if the name of your mapping is a bundle name. If you want to use this option to specify absolute paths you should prefix the path with the kernel parameters that exist in the DIC (for example%kernel.project_dir%).prefixA common namespace prefix that all documents of this mapping share. This prefix should never conflict with prefixes of other defined mappings otherwise some of your documents cannot be found by Doctrine. This option defaults to the application namespace +Document, for example for an application calledApp, the prefix would beApp\Document.aliasDoctrine offers a way to alias document namespaces to simpler, shorter names to be used in queries or for Repository access.is_bundleThis option is a derived value fromdirand by default is set to true if dir is relative proved by afile_exists()check that returns false. It is false if the existence check returns true. In this case an absolute path was specified and the metadata files are most likely in a directory outside of a bundle.
To avoid having to configure lots of information for your mappings you should follow these conventions:
- Put all your documents in a directory
Document/inside your project. For examplesrc/Document/. - If you are using xml or php mapping put all your configuration files
into either the
config/doctrine/directory (requires Symfony 5.4 or later) or theResources/config/doctrine/directory suffixed with mongodb.xml, mongodb.yml or mongodb.php respectively. - Attributes are assumed if a
Document/but noconfig/doctrine/orResources/config/doctrine/directory is found.
The following configuration shows a bunch of mapping examples:
doctrine_mongodb: document_managers: default: mappings: App: ~ App2: xml App3: { type: attribute, dir: Documents/ } App4: { type: xml, dir: config/doctrine/mapping } App5: type: xml dir: my-app-mappings-dir alias: AppAlias doctrine_extensions: type: xml dir: "%kernel.project_dir%/src/vendor/DoctrineExtensions/lib/DoctrineExtensions/Documents" prefix: DoctrineExtensions\Documents\ alias: DExt
Custom Types
Custom types can come in handy when you're missing a specific mapping type or when you want to replace the existing implementation of a mapping type for your documents.
doctrine_mongodb: types: custom_type: Fully\Qualified\Class\Name
Filters
Filter classes may be used in order to add criteria to ODM queries, regardless of where those queries are created within your application. Typically, filters will limit themselves to operating on a particular class or interface. Filters may also take parameters, which can be used to customize the injected query criteria.
Filters may be registered with a document manager by using the following syntax:
doctrine_mongodb: document_managers: default: filters: basic_filter: class: Vendor\Filter\BasicFilter enabled: true complex_filter: class: Vendor\Filter\ComplexFilter enabled: false parameters: author: bob comments: { $gte: 10 } tags: { $in: [ 'foo', 'bar' ] }
|
Unlike ORM, query parameters in MongoDB ODM may be non-scalar values. Since
such values are difficult to express in XML, the bundle allows JSON strings
to be used in |
Multiple Connections
If you need multiple connections and document managers you can use the following syntax:
doctrine_mongodb: default_database: hello_%kernel.environment% default_connection: conn2 default_document_manager: dm2 connections: conn1: server: mongodb://localhost:27017 conn2: server: mongodb://localhost:27017 document_managers: dm1: connection: conn1 database: db1 metadata_cache_driver: array mappings: App: ~ dm2: connection: conn2 database: db2 mappings: AnotherApp: ~
Now you can retrieve the configured services connection services:
$conn1 = $container->get('doctrine_mongodb.odm.conn1_connection');$conn2 = $container->get('doctrine_mongodb.odm.conn2_connection');
And you can also retrieve the configured document manager services which utilize the above connection services:
$dm1 = $container->get('doctrine_mongodb.odm.dm1_document_manager');$dm2 = $container->get('doctrine_mongodb.odm.dm2_document_manager');
Connecting to a pool of mongodb servers on 1 connection
It is possible to connect to several mongodb servers on one connection if
you are using a replica set by listing all of the servers within the connection
string as a comma separated list and using replicaSet option.
doctrine_mongodb: # ... connections: default: server: "mongodb://mongodb-01:27017,mongodb-02:27017,mongodb-03:27017/?replicaSet=replSetName"
Where mongodb-01, mongodb-02 and mongodb-03 are the machine hostnames. You can also use IP addresses if you prefer.
|
Please refer to Replica Sets manual of MongoDB PHP Driver for further details. |
Using Authentication on a Database Level
MongoDB supports authentication and authorisation on a database-level. This is mandatory if you have e.g. a publicly accessible MongoDB Server. To make use of this feature you need to configure credentials for each of your connections. Every connection needs also a database to authenticate against. The setting is represented by the authSource connection string. Otherwise you will get a auth failed exception.
doctrine_mongodb: # ... connections: default: server: "mongodb://localhost:27017" options: username: someuser password: somepass authSource: db_you_have_access_to
Using Queryable Encryption
For details on configuring Queryable Encryption (QE) and Client-Side Field-Level Encryption (CSFLE), see Client-Side Field-Level Encryption (CSFLE) and Queryable Encryption (QE).
Full Default Configuration
doctrine_mongodb: document_managers: # Prototype id: connection: ~ database: ~ default_document_repository_class: Doctrine\ODM\MongoDB\Repository\DocumentRepository default_gridfs_repository_class: Doctrine\ODM\MongoDB\Repository\DefaultGridFSRepository repository_factory: ~ persistent_collection_factory: ~ logging: true auto_mapping: false metadata_cache_driver: type: ~ class: ~ host: ~ port: ~ instance_class: ~ use_transactional_flush: false mappings: # Prototype name: mapping: true type: ~ dir: ~ prefix: ~ alias: ~ is_bundle: ~ types: # Prototype custom_type: Fully\Qualified\Class\Name connections: # Prototype id: server: ~ options: authMechanism: ~ connectTimeoutMS: ~ db: ~ authSource: ~ journal: ~ password: ~ readPreference: ~ readPreferenceTags: ~ replicaSet: ~ # replica set name socketTimeoutMS: ~ ssl: ~ tls: ~ tlsAllowInvalidCertificates: ~ tlsAllowInvalidHostnames: ~ tlsCAFile: ~ tlsCertificateKeyFile: ~ tlsCertificateKeyFilePassword: ~ tlsDisableCertificateRevocationCheck: ~ tlsDisableOCSPEndpointCheck: ~ tlsInsecure: ~ username: ~ retryReads: ~ retryWrites: ~ w: ~ wTimeoutMS: ~ driver_options: context: ~ # stream context to use for connection autoEncryption: # Options for client-side field-level encryption keyVaultClient: null # Service ID of a MongoDB\Driver\Manager for the key vault keyVaultNamespace: null # The namespace for the key vault collection (e.g., "encryption.__keyVault") kmsProvider: {} # Configuration for Key Management System provider (see specific examples above) # e.g., { type: "local", key: "YOUR_BASE64_KEY" } # e.g., { type: "aws", accessKeyId: "...", secretAccessKey: "..." } masterKey: ~ # Default master key to use when creating a new encrypted collection schemaMap: [] # Document schemas for explicit encryption encryptedFieldsMap: [] # Map of collections to their encrypted fields configuration extraOptions: [] # Extra options for mongocryptd # mongocryptdURI: "mongodb://localhost:27020" # mongocryptdBypassSpawn: false # mongocryptdSpawnPath: "/usr/local/bin/mongocryptd" # mongocryptdSpawnArgs: ["--idleShutdownTimeoutSecs=60"] # cryptSharedLibPath: null # Path to the crypt_shared library # cryptSharedLibRequired: false # If true, fails if the crypt_shared library cannot be loaded bypassQueryAnalysis: false # Disables automatic analysis of read and write operations for encryption bypassAutoEncryption: false # Disables auto-encryption tlsOptions: # TLS options for the Key Vault client (if keyVaultClient is not specified) tlsCAFile: null # Path to CA file, e.g., /path/to/key-vault-ca.pem tlsCertificateKeyFile: null # Path to client cert/key file, e.g., /path/to/key-vault-client.pem tlsCertificateKeyFilePassword: null # Password for client cert/key file tlsDisableOCSPEndpointCheck: false # Disable OCSP checks proxy_namespace: MongoDBODMProxies proxy_dir: "%kernel.cache_dir%/doctrine/odm/mongodb/Proxies" auto_generate_proxy_classes: 0 hydrator_namespace: Hydrators hydrator_dir: "%kernel.cache_dir%/doctrine/odm/mongodb/Hydrators" auto_generate_hydrator_classes: 0 persistent_collection_namespace: PersistentCollections persistent_collection_dir: "%kernel.cache_dir%/doctrine/odm/mongodb/PersistentCollections" auto_generate_persistent_collection_classes: 0 default_document_manager: ~ default_connection: ~ default_database: default
