### Service Repository Example
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/first_steps.rst
Example of a custom repository class intended to be used as a service, demonstrating dependency injection.
```php
// src/App/Repository/ProductRepository.php
namespace App\Repository;
use App\Document\Product;
use Doctrine\Bundle\MongoDBBundle\ManagerRegistry;
use Doctrine\Bundle\MongoDBBundle\Repository\ServiceDocumentRepository;
/**
* Remember to map this repository in the corresponding document's repositoryClass.
* For more information on this see the previous chapter.
*/
class ProductRepository extends ServiceDocumentRepository
{
```
--------------------------------
### Install Doctrine MongoDB Bundle
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/installation.rst
Install the Doctrine MongoDB Bundle using Composer. This command should be run after allowing contrib recipes if using Symfony Flex.
```bash
composer require doctrine/mongodb-odm-bundle
```
--------------------------------
### Fixture with Dependencies
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/data_fixtures.rst
Implement DependentFixtureInterface to specify fixture loading order. This example shows CategoryFixtures must load before ProductFixtures.
```php
// src/DataFixtures/CategoryFixtures.php
namespace App\DataFixtures;
use App\Document\Category;
use Doctrine\Bundle\MongoDBBundle\Fixture\Fixture;
use Doctrine\Persistence\ObjectManager;
class CategoryFixtures extends Fixture
{
public function load(ObjectManager $manager): void
{
$category = new Category();
$category->setName('Electronics');
$manager->persist($category);
$manager->flush();
// Store a reference for other fixtures to use
$this->addReference('category-electronics', $category);
}
}
// src/DataFixtures/ProductFixtures.php
namespace App\DataFixtures;
use App\Document\Product;
use Doctrine\Bundle\MongoDBBundle\Fixture\Fixture;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Persistence\ObjectManager;
class ProductFixtures extends Fixture implements DependentFixtureInterface
{
public function load(ObjectManager $manager): void
{
$product = new Product();
$product->setName('Laptop');
$product->setPrice(999.99);
$product->setCategory($this->getReference('category-electronics'));
$manager->persist($product);
$manager->flush();
}
public function getDependencies(): array
{
return [CategoryFixtures::class];
}
}
```
--------------------------------
### Install Doctrine Data Fixtures
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/data_fixtures.rst
Install the doctrine/data-fixtures package using Composer. This is a development dependency.
```bash
composer require --dev doctrine/data-fixtures
```
--------------------------------
### Configure Doctrine MongoDB Connections and Document Managers
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Configure connections and document managers using the Symfony configuration system. This example shows how to set up two connections and two document managers with specific mappings.
```php
use Symfony\Config\DoctrineMongodbConfig;
use function Symfony\Component\DependencyInjection\Loader\Configurator\param;
return static function (DoctrineMongodbConfig $config): void {
$config->defaultDatabase('hello_' . param('kernel.environment'));
$config->defaultDocumentManager('dm2');
$config->defaultConnection('dm2');
$config->connection('conn1')
->server('mongodb://localhost:27017');
$config->connection('conn2')
->server('mongodb://localhost:27017');
$config->documentManager('dm1')
->connection('conn1')
->database('db1')
->metadataCacheDriver('array')
->mapping('App');
$config->documentManager('dm2')
->connection('conn2')
->database('db2')
->mapping('AnotherApp');
};
```
--------------------------------
### Get Help for a Specific Doctrine MongoDB Command
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/console.rst
Use the 'help' command followed by the command name to get detailed information about a specific task, such as 'doctrine:mongodb:query'.
```bash
php bin/console help doctrine:mongodb:query
```
--------------------------------
### Configure Doctrine MongoDB Mappings (YAML)
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
YAML configuration for defining document managers and their mappings. This example shows various mapping types (attribute, XML, PHP) and directory configurations.
```yaml
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"
```
--------------------------------
### Render Registration Form in Twig Template
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/cookbook/registration_form.rst
A basic Twig template to render the form, including start, widgets, and end tags.
```html+jinja
{# templates/Account/register.html.twig #}
{{ form_start(form, {'action': path('create'), 'method': 'POST'}) }}
{{ form_widget(form) }}
{{ form_end(form) }}
```
--------------------------------
### Get and Check Entity Reference in Fixtures
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/data_fixtures.rst
Use getReference to retrieve an entity by its reference name. Use hasReference to check if a reference exists before attempting to retrieve it.
```php
$product = $this->getReference('my-product');
// Check if a reference exists
if ($this->hasReference('my-product')) {
$product = $this->getReference('my-product');
}
```
--------------------------------
### Common Repository Fetching Methods
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/first_steps.rst
Demonstrates basic methods for retrieving documents from a repository: find by ID, find all, and find by a specific field.
```php
// query by the identifier (usually "id")
$product = $repository->find($id);
// find *all* products
$products = $repository->findAll();
// find a group of products based on an arbitrary field value
$products = $repository->findBy(['price' => 19.99]);
```
--------------------------------
### Register Repositories as Services (XML)
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/first_steps.rst
Configure your repository directory to be automatically registered as services using autowiring and autoconfiguration. This simplifies dependency injection for your custom repositories.
```xml
```
--------------------------------
### Configure ODM Settings
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Set up default repository classes, repository factories, logging, and auto-mapping. Also configures metadata cache drivers and mapping details.
```php
$config->defaultGridfsRepositoryClass('')
->repositoryFactory('')
->logging(true)
->autoMapping(false)
->metadataCacheDriver()
->type(null)
->class(null)
->host(null)
->port(null)
->instanceClass(null)
->mapping('name')
->type('')
->dir('')
->prefix('')
->alias('')
->isBundle('')
->profiler()
->enabled(true)
->pretty(false)
;
```
--------------------------------
### Register Repositories as Services (YAML)
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/first_steps.rst
Configure your repository directory to be automatically registered as services using autowiring and autoconfiguration. This simplifies dependency injection for your custom repositories.
```yaml
# config/services.yaml
services:
_defaults:
autowire: true
autoconfigure: true
App\Repository\:
resource: '../src/Repository/*'
```
--------------------------------
### List Available Doctrine MongoDB Commands
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/console.rst
Run the console without arguments to see a list of all available commands, including those prefixed with 'doctrine:mongodb'.
```bash
php bin/console
```
--------------------------------
### Create Fixture Implementing ODMFixtureInterface
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/data_fixtures.rst
Alternatively, implement the ODMFixtureInterface directly. Ensure you have the necessary imports.
```php
namespace App\DataFixtures;
use App\Document\Product;
use Doctrine\Bundle\MongoDBBundle\Fixture\ODMFixtureInterface;
use Doctrine\Persistence\ObjectManager;
class ProductFixtures implements ODMFixtureInterface
{
public function load(ObjectManager $manager): void
{
$product = new Product();
$product->setName('Example Product');
$product->setPrice(19.99);
$manager->persist($product);
$manager->flush();
}
}
```
--------------------------------
### Add Mapping Information with XML Configuration
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/first_steps.rst
Configure mapping metadata for the Product class using XML. This is an alternative to using PHP attributes.
```xml
```
--------------------------------
### Store and Retrieve References
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/data_fixtures.rst
Use addReference() to store a document and getReference() to retrieve it in other fixtures. This is crucial for establishing relationships between fixtures.
```php
// Store a reference
$this->addReference('my-product', $product);
// Retrieve a reference
```
--------------------------------
### Persist a Product Document to MongoDB
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/first_steps.rst
Instantiate a Product object, set its properties, and use the DocumentManager to persist and flush the changes to MongoDB. Ensure a route is configured to access this controller action.
```php
// src/App/Controller/ProductController.php
use App\Document\Product;
use Doctrine\ODM\MongoDB\DocumentManager;
use Symfony\Component\HttpFoundation\Response;
// ...
public function createAction(DocumentManager $dm)
{
$product = new Product();
$product->setName('A Foo Bar');
$product->setPrice('19.99');
$dm->persist($product);
$dm->flush();
return new Response('Created product id ' . $product->getId());
}
```
--------------------------------
### Load Fixtures via Console
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/data_fixtures.rst
Load all registered fixtures using the doctrine:mongodb:fixtures:load console command.
```bash
php bin/console doctrine:mongodb:fixtures:load
```
--------------------------------
### Use Custom Repository Method
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/first_steps.rst
Call custom repository methods to retrieve data, similar to using default finder methods.
```php
$products = $dm->getRepository(Product::class)
->findAllOrderedByName();
```
--------------------------------
### Basic Doctrine MongoDB Configuration (PHP)
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Configure connections, default database, document managers, and mappings using PHP. This programmatic approach offers flexibility in defining configuration.
```php
use Symfony\Config\DoctrineMongodbConfig;
use function Symfony\Component\DependencyInjection\Loader\Configurator\env;
use function Symfony\Component\DependencyInjection\Loader\Configurator\param;
return static function (DoctrineMongodbConfig $config): void {
$config->connection('default')
->server(env('MONGODB_URI')->default('mongodb://localhost:27017')->resolve())
->options([]);
$config->defaultDatabase('hello_' . param('kernel.environment'));
$config->documentManager('default')
->mapping('App')
->isBundle(false)
->dir(param('kernel.project_dir') . '/src/Document')
->prefix('App\Document')
->alias('App')
->metadataCacheDriver('array'); // array, service, apcu, memcached, redis
};
```
--------------------------------
### Basic Doctrine MongoDB Configuration
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/installation.rst
Configure the default connection, default database, and enable auto-mapping for document managers in the doctrine_mongodb.yaml file.
```yaml
# config/packages/doctrine_mongodb.yaml
doctrine_mongodb:
connections:
default:
server: "%mongodb_server%"
options: {}
default_database: test_database
document_managers:
default:
auto_mapping: true
```
--------------------------------
### Fetch a Product by ID using Repository
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/first_steps.rst
Retrieves a single Product document from MongoDB using its ID. Ensure the DocumentManager and Product class are correctly configured.
```php
public function showAction(DocumentManager $dm, $id)
{
$product = $dm->getRepository(Product::class)->find($id);
if (! $product) {
throw $this->createNotFoundException('No product found for id ' . $id);
}
// do something, like pass the $product object into a template
}
```
--------------------------------
### Accessing the Repository
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/first_steps.rst
Obtain the repository for a specific document class to interact with its methods for fetching objects.
```php
$repository = $dm->getRepository(Product::class);
```
--------------------------------
### Basic Doctrine MongoDB Configuration (XML)
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Configure connections, default database, document managers, and mappings using XML. This format is an alternative to YAML for Symfony configuration.
```xml
```
--------------------------------
### Configure Doctrine MongoDB Bundle (PHP)
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Use this PHP configuration to set up Doctrine MongoDB ODM programmatically. It mirrors the XML configuration options for flexibility.
```php
use Symfony\Config\DoctrineMongodbConfig;
return static function (DoctrineMongodbConfig $config): void {
$config->autoGenerateHydratorClasses(0);
$config->autoGenerateProxyClasses(0);
$config->enableNativeLazyObjects(true); // Enabled by default if PHP 8.4+ and doctrine/mongodb-odm 2.14+ are installed
$config->enableLazyGhostObjects(true); // Enabled by default if doctrine/mongodb-odm 2.10+ is installed
$config->defaultConnection('');
$config->defaultDatabase('default');
$config->defaultDocumentManager('');
$config->hydratorDir('%kernel.cache_dir%/doctrine/odm/mongodb/Hydrators');
$config->hydratorNamespace('Hydrators');
$config->proxyDir('%kernel.cache_dir%/doctrine/odm/mongodb/Proxies');
$config->proxyNamespace('Proxies');
$config->documentManager('id')
->connection('')
->database('')
->defaultDocumentRepositoryClass('')
```
--------------------------------
### Enable Doctrine MongoDB Bundle Manually
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/installation.rst
Manually enable the Doctrine MongoDB Bundle by adding its class to the config/bundles.php file if not using Symfony Flex.
```php
// config/bundles.php
return [
// ...
Doctrine\Bundle\MongoDBBundle\DoctrineMongoDBBundle::class => ['all' => true],
];
```
--------------------------------
### Append Fixtures Without Truncating
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/data_fixtures.rst
Use the --append flag with the load command to add fixture data without truncating the database first.
```bash
# Append fixtures without truncating the database
php bin/console doctrine:mongodb:fixtures:load --append
```
--------------------------------
### Basic Doctrine MongoDB Configuration (YAML)
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Configure connections, default database, document managers, and mappings using YAML. This is the standard configuration format for Symfony applications.
```yaml
# config/packages/doctrine_mongodb.yaml
doctrine_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
```
--------------------------------
### Configure Custom Repository with XML
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/first_steps.rst
Define a custom repository class for your document using XML in the mapping definition.
```xml
```
--------------------------------
### Configure Document Manager Mappings (PHP)
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Configures document manager settings and mappings using PHP. This approach is useful for dynamic configuration within your application.
```php
use Symfony\Config\DoctrineMongodbConfig;
use function Symfony\Component\DependencyInjection\Loader\Configurator\param;
return static function (DoctrineMongodbConfig $config): void {
$config->documentManager('default')
->mapping('App')
->mapping('App2')
->type('xml')
->mapping('App3')
->type('attribute')
->dir('Documents/')
->mapping('App4')
->type('xml')
->dir('config/doctrine/mapping')
->mapping('App5')
->type('xml')
->dir('my-app-mappings-dir')
->alias('AppAlias')
->mapping('doctrine_extensions')
->type('xml')
->dir(param('kernel.project_dir') . '/src/vendor/DoctrineExtensions/lib/DoctrineExtensions/Documents')
->prefix('DoctrineExtensions\\Documents\\')
->alias('DExt')
;
}
```
--------------------------------
### Registering a Listener with PHP Attributes
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/events.rst
Use the #[AsDocumentListener] attribute to register a listener for a specific event. The 'event' attribute is required, and 'priority' and 'connection' can be optionally specified.
```php-attributes
namespace App\EventListener;
use Doctrine\Bundle\MongoDBBundle\Attribute\AsDocumentListener;
use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs;
#[AsDocumentListener('postPersist', priority: 500, connection: 'default')]
class SearchIndexer
{
public function postPersist(LifecycleEventArgs $event): void
{
// ...
}
}
```
--------------------------------
### Set Custom Type
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Configure a custom document type by specifying its type name and fully qualified class name.
```php
$config->type('custom_type')
->class('Fully\Qualified\Class\Name');
```
--------------------------------
### Specify Automatic Encryption Shared Library Path (PHP)
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/encryption.rst
Configure the path to the Automatic Encryption Shared Library in PHP. This is necessary if the driver cannot find it by default.
```php
use Symfony\Config\DoctrineMongodbConfig;
return static function (DoctrineMongodbConfig $config): void {
$config->connection('default')
->autoEncryption([
'extraOptions' => [
'cryptSharedLibPath' => '%kernel.project_dir%/bin/mongo_crypt_v1.so',
],
]);
};
```
--------------------------------
### Configure Doctrine MongoDB Document Manager and Connection (PHP)
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Use this PHP configuration to set up a default document manager with a Memcached cache driver and a MongoDB connection. It demonstrates how to dynamically set the database name based on the environment.
```php
use Symfony\Component\Cache\Adapter\MemcachedAdapter;
use Symfony\Config\DoctrineMongodbConfig;
use function Symfony\Component\DependencyInjection\Loader\Configurator\param;
return static function (DoctrineMongodbConfig $config): void {
$config->defaultDatabase('hello_' . param('kernel.environment'));
$config->connection('default')
->server('mongodb://localhost:27017')
->options([]);
$config->documentManager('default')
->mapping('App')
->metadataCacheDriver()
->type('memcached')
->class(MemcachedAdapter::class)
->host('localhost')
->port(11211)
->instanceClass("Memcached"::class)
;
};
```
--------------------------------
### Configure Multiple Connections and Document Managers in YAML
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Set up multiple MongoDB connections and document managers using YAML configuration. This allows for distinct database configurations within the same application.
```yaml
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: ~
```
--------------------------------
### Configure TLS Options for Key Vault Client (YAML)
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/encryption.rst
Set TLS options for the internal key vault client when a custom keyVaultClient service is not specified. This includes CA file, client certificate, and password.
```yaml
doctrine_mongodb:
connections:
default:
autoEncryption:
tlsOptions:
tlsCAFile: "/path/to/key-vault-ca.pem"
tlsCertificateKeyFile: "/path/to/key-vault-client.pem"
tlsCertificateKeyFilePassword: "keyvaultclientpassword"
tlsDisableOCSPEndpointCheck: false
```
--------------------------------
### Configure Custom Repository with PHP Attributes
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/first_steps.rst
Define a custom repository class for your document using PHP attributes in the mapping definition.
```php-attributes
// src/Document/Product.php
namespace App\Document;
use App\Repository\ProductRepository;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
#[MongoDB\Document(repositoryClass: ProductRepository::class)]
class Product
{
// ...
}
```
--------------------------------
### Configure Local KMS Provider (PHP)
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/encryption.rst
Configure the 'autoEncryption' option with a local KMS provider and master key using Symfony's configuration builder. Ensure the key is Base64 encoded.
```php
use Symfony\Config\DoctrineMongodbConfig;
return static function (DoctrineMongodbConfig $config): void {
$config->connection('default')
->server('mongodb://localhost:27017')
->autoEncryption([
'kmsProvider' => [
'type' => 'local',
'key' => 'YOUR_BASE64_KEY',
],
// See below for more optional configuration
]);
};
```
--------------------------------
### Configure TLS Options for Key Vault Client (XML)
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/encryption.rst
Configure TLS settings for the key vault client using XML attributes. This allows specifying certificate files and password for secure connections.
```xml
```
--------------------------------
### Connect to a Pool of MongoDB Servers (Replica Set)
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Configure a single connection to a pool of MongoDB servers, typically a replica set. List all servers in the connection string and specify the 'replicaSet' option.
```yaml
doctrine_mongodb:
# ...
connections:
default:
server: "mongodb://mongodb-01:27017,mongodb-02:27017,mongodb-03:27017/?replicaSet=replSetName"
```
--------------------------------
### Create Fixture Extending Fixture Base Class
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/data_fixtures.rst
Create a fixture class by extending Doctrine\Bundle\MongoDBBundle\Fixture\Fixture. This provides convenient access to the object manager and reference functionality.
```php
namespace App\DataFixtures;
use App\Document\Product;
use Doctrine\Bundle\MongoDBBundle\Fixture\Fixture;
use Doctrine\Persistence\ObjectManager;
class ProductFixtures extends Fixture
{
public function load(ObjectManager $manager): void
{
$product = new Product();
$product->setName('Example Product');
$product->setPrice(19.99);
$manager->persist($product);
$manager->flush();
}
}
```
--------------------------------
### Configure MongoDB Connection
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Define connection details for a MongoDB instance, including server address, authentication, and advanced options like client-side field-level encryption.
```php
$config->connection('id')
->server('mongodb://localhost')
->autoEncryption([
'bypassAutoEncryption' => false,
'keyVaultClient' => null,
'keyVaultNamespace' => null,
'kmsProvider' => [
],
'schemaMap' => [],
'encryptedFieldsMap' => [],
'extraOptions' => [
],
'bypassQueryAnalysis' => false,
'tlsOptions' => [
],
])
->options([
'authMechanism' => null,
'connectTimeoutMS' => null,
'db' => null,
'authSource' => null,
'journal' => null,
'password' => null,
'readPreference' => null,
'readPreferenceTags' => null,
'replicaSet' => null,
'socketTimeoutMS' => null,
'ssl' => null,
'tls' => null,
'tlsAllowInvalidCertificates' => null,
'tlsAllowInvalidHostnames' => null,
'tlsCAFile' => null,
'tlsCertificateKeyFile' => null,
'tlsCertificateKeyFilePassword' => null,
'tlsDisableCertificateRevocationCheck' => null,
'tlsDisableOCSPEndpointCheck' => null,
'tlsInsecure' => null,
'username' => null,
'retryReads' => null,
'retryWrites' => null,
'w' => null,
'wTimeoutMS' => null,
]);
```
--------------------------------
### Define a Basic Document Class
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/first_steps.rst
Create a plain PHP class to represent a document. This class will later be mapped to a MongoDB collection.
```php
namespace App\Document;
class Product
{
protected $name;
protected $price;
}
```
--------------------------------
### Display Registration Form in Controller
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/cookbook/registration_form.rst
Creates a controller action to instantiate the registration form and render it in a Twig template.
```php
namespace App\Controller;
use App\Form\Model\Registration;
use App\Form\Type\RegistrationType;
use Doctrine\ODM\MongoDB\DocumentManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
class AccountController extends AbstractController
{
public function registerAction()
{
$form = $this->createForm(RegistrationType::class, new Registration());
return $this->render('Account/register.html.twig', [
'form' => $form->createView()
]);
}
}
```
--------------------------------
### Implement Custom Repository Method
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/first_steps.rst
Add a custom method to your repository class to encapsulate specific query logic, such as ordering documents by name.
```php
// src/Repository/ProductRepository.php
namespace App\Repository;
use Doctrine\ODM\MongoDB\Repository\DocumentRepository;
class ProductRepository extends DocumentRepository
{
public function findAllOrderedByName()
{
return $this->createQueryBuilder()
->sort('name', 'ASC')
->getQuery()
->execute();
}
}
```
--------------------------------
### Allow Contrib Recipes
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/installation.rst
Enable the usage of Contrib Recipes for DoctrineMongoDBBundle when using Symfony Flex.
```bash
composer config extra.symfony.allow-contrib true
```
--------------------------------
### Configure MongoDB Connection
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Define a MongoDB connection with server details and authentication options. This is typically done in your services.yaml or equivalent configuration.
```yaml
```
--------------------------------
### Configure Local KMS Provider (YAML)
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/encryption.rst
Configure the 'autoEncryption' option with a local KMS provider and master key. Ensure the key is Base64 encoded.
```yaml
doctrine_mongodb:
connections:
default:
server: "mongodb://localhost:27017"
autoEncryption:
kmsProvider:
type: local
key: "YOUR_BASE64_KEY"
# See below for more optional configuration
```
--------------------------------
### Connect to a Pool of MongoDB Servers (Replica Set) - PHP Config
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Configure a single connection to a pool of MongoDB servers using PHP configuration. This programmatic approach is useful for dynamic configuration.
```php
use Symfony\Config\DoctrineMongodbConfig;
return static function (DoctrineMongodbConfig $config): void {
$config->connection('default')
->server('mongodb://mongodb-01:27017,mongodb-02:27017,mongodb-03:27017/?replicaSet=replSetName');
};
```
--------------------------------
### Configure Automatic Encryption with TLS Options
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/encryption.rst
Set up automatic encryption for a MongoDB connection, specifying TLS options for secure communication. Ensure the certificate files and password are correct.
```php
use Symfony\Config\DoctrineMongodbConfig;
return static function (DoctrineMongodbConfig $config): void {
$config->connection('default')
->autoEncryption([
'tlsOptions' => [
'tlsCAFile' => '/path/to/key-vault-ca.pem',
'tlsCertificateKeyFile' => '/path/to/key-vault-client.pem',
'tlsCertificateKeyFilePassword' => 'keyvaultclientpassword',
'tlsDisableOCSPEndpointCheck' => false,
],
]);
};
```
--------------------------------
### Fetch Objects with Multiple Conditions and Ordering
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/first_steps.rst
Use findOneBy to fetch a single document matching multiple criteria, and findBy with sorting to retrieve multiple documents.
```php
// query for one product matching by name and price
$product = $repository->findOneBy(['name' => 'foo', 'price' => 19.99]);
// query for all products matching the name, ordered by price
$product = $repository->findBy(
['name' => 'foo'],
['price' => 'ASC']
);
```
--------------------------------
### Add Mapping Information with PHP Attributes
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/first_steps.rst
Use PHP 8 attributes to define metadata for mapping the Product class and its properties to MongoDB. Requires PHP 8.0+ and ODM Bundle 4.4+.
```php
namespace App\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
#[MongoDB\Document]
class Product
{
#[MongoDB\Id]
protected string $id;
#[MongoDB\Field(type: 'string')]
protected string $name;
#[MongoDB\Field(type: 'float')]
protected float $price;
}
```
--------------------------------
### Configure Doctrine MongoDB Bundle (XML)
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Use this XML configuration to set up Doctrine MongoDB ODM. It allows defining document managers, connections, metadata caching, and custom types.
```xml
```
--------------------------------
### Configure Document Manager Mappings (XML)
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Defines document manager configurations and mappings in XML format. Use this to specify document directories, mapping types, and aliases.
```xml
```
--------------------------------
### Connect to a Pool of MongoDB Servers (Replica Set) - XML
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Configure a single connection to a pool of MongoDB servers using XML configuration. This is an alternative to YAML for specifying replica set connections.
```xml
```
--------------------------------
### Define Registration Form Model
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/cookbook/registration_form.rst
Creates a model for the registration form, including a User object and a boolean field for terms acceptance. Includes validation constraints for these fields.
```php
namespace App\Form\Model;
use App\Document\User;
use Symfony\Component\Validator\Constraints as Assert;
class Registration
{
/**
* @Assert\Type(type="App\Document\User")
*/
protected $user;
/**
* @Assert\NotBlank()
* @Assert\IsTrue()
*/
protected $termsAccepted;
public function setUser(User $user)
{
$this->user = $user;
}
public function getUser()
{
return $this->user;
}
public function getTermsAccepted()
{
return $this->termsAccepted;
}
}
```
--------------------------------
### Registering a Listener with YAML Configuration
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/events.rst
Configure event listeners using the 'doctrine_mongodb.odm.event_listener' tag in your services.yaml. The 'event' key is mandatory, and 'priority' and 'connection' are optional.
```yaml
services:
# ...
App\EventListener\SearchIndexer:
tags:
-
name: 'doctrine_mongodb.odm.event_listener'
# this is the only required option for the lifecycle listener tag
event: 'postPersist'
# listeners can define their priority in case multiple subscribers or listeners are associated
# to the same event (default priority = 0; higher numbers = listener is run earlier)
priority: 500
# you can also restrict listeners to a specific Doctrine connection
connection: 'default'
```
--------------------------------
### Configure MongoDB Connection with PHP
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Programmatically configure a MongoDB connection using PHP. This approach is useful for dynamic configurations or within custom build scripts.
```php
use Symfony\Config\DoctrineMongodbConfig;
return static function (DoctrineMongodbConfig $config): void {
$config->connection('default')
->server('mongodb://localhost:27017')
->options([
'username' => 'someuser',
'password' => 'somepass',
'authSource' => 'db_you_have_access_to',
]);
};
```
--------------------------------
### Configure MongoDB Authentication (XML)
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Configure authentication credentials for a MongoDB connection using XML. This provides an alternative to YAML for setting up user credentials and authentication source.
```xml
```
--------------------------------
### Specify Automatic Encryption Shared Library Path (XML)
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/encryption.rst
Set the path for the Automatic Encryption Shared Library using XML configuration.
```xml
```
--------------------------------
### Configure MongoDB Server Parameter
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/installation.rst
Set the MongoDB server connection string as a parameter in services.yaml. This is a prerequisite for the doctrine_mongodb.yaml configuration.
```yaml
# config/services.yaml
parameters:
mongodb_server: "mongodb://localhost:27017"
```
--------------------------------
### Configure Document Manager Filters in PHP
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Configure document manager filters and their parameters programmatically using PHP. This method allows for dynamic parameter setting and is useful for complex configurations.
```php
use Symfony\Config\DoctrineMongodbConfig;
return static function (DoctrineMongodbConfig $config): void {
$config->documentManager('default')
->filter('basic_filter')
->class(\Vendor\Filter\BasicFilter::class)
->enabled(true)
->filter('complex_filter')
->class(\Vendor\Filter\ComplexFilter::class)
->enabled(false)
->parameter('author', 'bob')
->parameter('comments', [ '$gte' => 10 ])
->parameter('tags', [ '$in' => [ 'foo', 'bar' ] ])
;
}
```
--------------------------------
### Automatic Fetching by Identifier and Property
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/first_steps.rst
The resolver automatically fetches documents by identifier if {id} is in the route, or attempts a findOneBy() using route wildcards that match document properties.
```php
/**
* Fetch via identifier because {id} is in the route.
*/
#[Route('/product/{id}')]
public function showByIdentifier(Post $post): Response
{
}
```
```php
/**
* Perform a findOneBy() where the slug property matches {slug}.
*/
#[Route('/product/{slug}')]
public function showBySlug(Post $post): Response
{
}
```
--------------------------------
### Fetch via Expression with MapDocument
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/first_steps.rst
Use the MapDocument attribute with an expression to define custom fetching logic when automatic fetching is insufficient. Route wildcards are available as variables within the expression.
```php
#[Route('/product/{product_id}')]
public function show(
#[MapDocument(expr: 'repository.find(product_id)')]
Product $product
): Response {
}
```
```php
#[Route('/product/{id}/comments/{comment_id}')]
public function show(
Product $product,
#[MapDocument(expr: 'repository.find(comment_id)')]
Comment $comment
): Response {
}
```
--------------------------------
### Automatic Document Fetching with DocumentValueResolver
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/first_steps.rst
Simplifies controller actions by automatically resolving document objects from route parameters. This feature is enabled by default.
```php
// src/Controller/ProductController.php
namespace App\Controller;
use App\Document\Product;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
// ...
#[Route('/product/{id}')]
public function showAction(Product $product): Response
{
// use the Product!
// do something, like pass the $product object into a template
}
```
--------------------------------
### Memcached Metadata Cache Configuration (YAML)
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Configure Memcached as the metadata cache driver. This requires specifying the cache type, class, host, and port for the Memcached instance.
```yaml
# app/config/config.yml
doctrine_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
```
--------------------------------
### Configure MongoDB Authentication (YAML)
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Configure authentication credentials for a MongoDB connection using YAML. This is essential for securing publicly accessible MongoDB servers.
```yaml
doctrine_mongodb:
# ...
connections:
default:
server: "mongodb://localhost:27017"
options:
username: someuser
password: somepass
authSource: db_you_have_access_to
```
--------------------------------
### Registering a Listener with XML Configuration
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/events.rst
Define event listeners in services.xml using the 'doctrine_mongodb.odm.event_listener' tag. The 'event' attribute is required, while 'priority' and 'connection' are optional.
```xml
```
--------------------------------
### Configure Multiple Connections and Document Managers in XML
Source: https://github.com/doctrine/doctrinemongodbbundle/blob/5.7.x/docs/config.rst
Define multiple MongoDB connections and document managers using XML configuration. This approach is suitable for applications requiring segregated database access.
```xml
```