A couple of weeks ago we showed how you could set indexes in your MongoDB documents when using Doctrine ODM and Symfony2.

Of course you can define unique indexes to prevent duplicate values and there are a couple of different syntax options to do so, which are clearly defined in the official documentation.

But defining and creating the indexes is not enough. You must specify when you want to enforce the constraint, this is due to the fact that the PHP driver needs to tell MongoDB to throw an error when a duplicate key is found. To enforce the constraint, you must pass safe=>true to the flush() operation:

/* @var $dm DocumentManager */