Saturday, November 26, 2011

Mapping embedded documents in Doctrine MongoDB ODM

If you have a MongoDB document that has another document embedded in it, you still have to create a separate XML mapping document for the embedded one. So if you have a parent document called Activity that has an embedded document called Coordinates, the configuration would look something like this:

src/Acme/ActivityBundle/Resources/config/doctrine/Activity.mongodb.xml

<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
                    http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">

    <document name="Acme\ActivityBundle\Document\Activity" db="acme" collection="activity" customId="true">
        
        <field fieldName="id" id="true" strategy="INCREMENT" />

        <embed-one target-document="Acme\ActivityBundle\Document\Coordinates" field="locationCoordinates" />

        <lifecycle-callbacks>
            <lifecycle-callback method="callbackPrePersist" type="prePersist" />
            <lifecycle-callback method="callbackPreUpdate" type="preUpdate" />
        </lifecycle-callbacks>
        
        <indexes>
            <index>
                <key name="locationCoordinates" order="2d" />
            </index>
        </indexes>
        
    </document>
    
</doctrine-mongo-mapping>

src/Acme/ActivityBundle/Resources/config/doctrine/Coordinates.mongodb.xml

<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
                    http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">

    <embedded-document name="Acme\ActivityBundle\Document\Coordinates">
        <field fieldName="latitude" type="float" />
        <field fieldName="longitude" type="float" />
    </embedded-document>
    
</doctrine-mongo-mapping>

The XML mapping format is not included in the Doctrine MongoDB ODM documentation. After a bunch of tests, I realized the @EmbeddedDocument in the annotation format example and simply replaced the document tag with embedded-document in the mapping file.

No comments:

Post a Comment