Question

I'm working on a Symfony 2 project using DoctrineMongoDBBundle to manage data. I need to deal with two or more instances but I didn't find any help to configure.

The documentation explains how to configure one default connection by adding the following code in the config.yml file.

doctrine_mongodb:
    connections:
        default:
            server: mongodb://localhost:27017
            options: {}
    default_database: test_database
    document_managers:
        default:
            auto_mapping: true

And to call the document manager I used that code :

 $dm = $this->get('doctrine_mongodb')->getManager();

It works well but I don't find how to configure more connections and how to deal with by using the Document Manager. I think it should looks like the following source but I don't find how to call a specific connection.

doctrine_mongodb:
    connections:
        default:
            server: mongodb://localhost:27017
            options: {}
        second:
            server: mongodb://localhost:27018
            options: {}
    default_database: test_database
    document_managers:
        default:
            auto_mapping: true
        second:
            auto_mapping: true

Any idea ?!

Thanks !

Was it helpful?

Solution

This example is covered in the Multiple Connections section of the bundle's config reference. Each connection and document manager should have a unique name, and then the document manager configuration should refer to the appropriate connection name. I believe the last bit is what was missing from your original example. Quoting the bundle docs:

doctrine_mongodb:
    default_database: hello_%kernel.environment%
    default_connection: conn2
    default_document_manager: dm2
    metadata_cache_driver: apc
    connections:
        conn1:
            server: mongodb://a.example.com:27017
        conn2:
            server: mongodb://b.example.com:27017
    document_managers:
        dm1:
            connection: conn1
            metadata_cache_driver: xcache
            mappings:
                AcmeDemoBundle: ~
        dm2:
            connection: conn2
            mappings:
                AcmeHelloBundle: ~

I would suggest using names other than "default" for your connections and document managers, to avoid confusion. Take note that the document manager names will now be part of the service ID. Per the above configuration, the second connection and document manager will be aliased as the default service IDs (see: default_connection and default_document_manager). Quoting a second example from the documentation, the specific service IDs will be:

$conn1 = $container->get('doctrine_mongodb.odm.conn1_connection');
$conn2 = $container->get('doctrine_mongodb.odm.conn2_connection');
$dm1 = $container->get('doctrine_mongodb.odm.dm1_document_manager');
$dm2 = $container->get('doctrine_mongodb.odm.dm2_document_manager');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top