Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create an index in mongoengine to be unique=True and sparse=True

I am using mongoengine with flask. I have a db.Document class called profile in which i want a field to be nullable and unique, i understand the way to do this is to make an index of that field that is both sparse=True and unique=True, how do i go about doing this?

like image 644
Jay Avatar asked Sep 13 '12 10:09

Jay


2 Answers

You will have to declare the index in the meta definition eg:

class BlogPost(Document):
    date = DateTimeField(db_field='addDate', default=datetime.now)
    category = StringField()
    tags = ListField(StringField())

    meta = {
        'indexes': [
            {'fields': ['-date'], 'unique': True,
              'sparse': True, 'types': False },
        ],
    }
like image 155
Ross Avatar answered Oct 27 '22 05:10

Ross


In case of unique constraint you can set it with the field declaration as:

email = mongodb.EmailField(required=True, unique=True)
like image 29
Eldelshell Avatar answered Oct 27 '22 05:10

Eldelshell