Search code examples
mongodbsymfonysymfony-2.1doctrine-odm

Can there be an issue if Mongo class is instanced twice?


I want to use MongoDB for storing sessions, and I need to inject the \Mongo object into the session handler.

I first thought I could fetch it from doctrine with something like this:

services:
    mongo.connection:
        class: MongoDoctrine\MongoDB\Connection
        factory_service: doctrine.odm.mongodb.document_manager
        factory_method: getConnection
    mongo:
        class: Mongo
        factory_service: mongo.connection
        factory_method: getMongo

But it throws a circular reference exception due to a logger preprocessor I'm using that needs the request_id I think, and even if I turn that off, sometimes it returns null. So then I just instantiated my own instance of Mongo and worked fine:

services:
    mongo:
        class: Mongo
        arguments: [ %doctrine_mongodb.default_server% , %doctrine_mongodb.options% ]

Can there be a problem with this? I mean doctrine and the session handler will be using two different instances of \Mongo.

Any ideas on how to get the reference to the \Mongo object created by doctrine without falling into a circular reference?


Solution

  • Every instance of Mongo represents a separate network connection to the cluster. The documentation recommends to use only a single instance for the whole application.

    When you frequently create new Mongo instances, each instance must first establish a new connection, which will take considerable time. But reusing an old instance means that the already open network connection will be used, which is much faster.

    Another drawback of using multiple instances is that MongoDB guarantees that all queries send through each connection are processed in-order, but doesn't guarantee the same for queries coming from different connections. So when you first create a document and then you delete it with the same connection, you can be sure it's gone. But when you create it via Mongo A and then delete it via Mongo B, it is possible that the save will be processed after the remove and the object will stay in the database.