test.ical.ly | getting the web by the balls

Aug/11

25

Using a unique index in MongoDB with Doctrine ODM and Symfony2

Just spent about an hour yesterday to figure out how to use unique indexes in a MongoDB document. It involves three simple steps.

I couldn’t get these right as they seem not to be documented in one place. With the help of two ServerGrove posts here and here I found out how to proceed.

1. Add your unique constraint to your document

 

For other ways to specify unique indexes please refer to the official documentation.

2. Tell the document manager to create them

Apparently this does not happen automatically as you might expect.

3. Enforce the constraints in your code

It seems MongoDB would not fail on duplicate insert if you don’t tell it to.

Hope this helps someone.

· · ·



  • Henrik

    To create the collections and indexes you can run:

    php app/console doctrine:mongodb:schema:create

    This command can be run multiple times (if you add new indexes for example).

  • http://test.ical.ly Christian

    @Henrik thanks for the info. Does this command create the indexes automatically?

  • Henrik

    @Christian: yes, there is a –index option which is true by default (see php app/console help doctrine:mongodb:schema:create).

  • http://test.ical.ly Christian

    @Henrik thanks! I didn’t know about that one. Actually I haven’t been using the commands at all so far..

  • http://twitter.com/ludofleury Ludovic Fleury

    Hey, the last line :
    $dm->flush(array(‘safe’=>true));
    isn’t about “consistency”. It’s about sync write. By default mongodb write are async, so you can’t get the status of the write in PHP (sync exec).

    When you use “safe”, you ask for a sync write, mongodb will ensure the data are flushed on disk before returning anything (so you can get your error here).

  • caefer

    @twitter-47574527:disqus thanks for clearing tht up! :)

<<

>>

Theme Design by devolux.nh2.me