Mongoengine: Manage field with unique=true and required=false

Created on 7 Jul 2017  路  8Comments  路  Source: MongoEngine/mongoengine

When i define a field with unique=true and required=flase as parameter, the validator doesn't permits to have 2 object with this field set None. There's a workaround for this?
Maybe it would be interesting to add this functionality to mongoengine, leaving to the developer to allow multiple values set to none or not.

What do you thinks about that?

Most helpful comment

This is how you can define a partial index which supports unique with null values

class User(Document)
   username = StringField(null=True)
   city = StringField()


   meta = {"indexes": [
        "city",     # normal index
        {"fields": ["username",],
            "unique": True,
            "partialFilterExpression": {
                "username": {"$type": "string"}
            }
        },
    ]}

All 8 comments

In any database management system, there is only one null value permitted when you set unique constraint. It is nothing about mongoengine.

If you're using MongoDB v3.2+, you could use a partial index with a unique constraint to index only non-null values.

Thanks you! That's what I was looking for.

@Buckler89
How did you enforce the Partial Index with Unique Constraint in mongoengine

Ping. Same question.

Anyone willing to share a solution?

This is how you can define a partial index which supports unique with null values

class User(Document)
   username = StringField(null=True)
   city = StringField()


   meta = {"indexes": [
        "city",     # normal index
        {"fields": ["username",],
            "unique": True,
            "partialFilterExpression": {
                "username": {"$type": "string"}
            }
        },
    ]}

@pankajkgarg It worked perfectly for me, thanks!!

Was this page helpful?
0 / 5 - 0 ratings