Search code examples
mongodbdoctrine-ormzend-framework2

How to create UniqueIndex and nullable string field in doctrine 2?


In a collection I have a string field that can be null some times. But, If that field has a value, it should be unique.I have tried like this,

/** @ODM\Field(type="string", nullable=true) @ODM\UniqueIndex(order="asc") */
private $empId;

I am using mongodb 3.0 ,doctrine 2 ORM on Zend Framework 2

Anyone know something on how to do that or if it's possible ?


Solution

  • Using mongodb sparse option, I can achieve above scenario.

    /** @ODM\Field(type="string" ) @ODM\UniqueIndex(sparse=true) */
    private $empId;
    

    See more: https://docs.mongodb.com/manual/core/index-sparse/
    http://docs.doctrine-project.org/projects/doctrine-mongodb-odm/en/latest/reference/indexes.html