Search code examples
indexinguniquemongoenginesparse-matrix

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?


Solution

  • 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 },
            ],
        }