'How to add collation in indexes for mongodb?

I work with Mongoengine in Django, got task to sort by first_name, last_name fields ignoring case and leading whitespaces

that is why add collation in queryset:

collation = dict(
    locale='en',
    caseLevel=False,
    caseFirst='off',
    strength=3,
    numericOrdering=True,
    alternate='shifted',
    maxVariable='space',
    backwards=False,
)

return queryset.collation(collation).order_by('-is_stocked', 'brand', 'model')

Unfortunetly, my queryset takes too long time

I want to speed up it, so start to read about mongodb indexes, but don't understand how add it properly, I tried this: models.py

class Car(UpdatedAtTimestampMixin, Document):
    model = fields.StringField(null=True, db_field='model')
    brand = fields.StringField(null=True, db_field='brand')
    is_stocked = fields.BooleanField(db_field='isStocked')

    meta = {
        'collection': 'books',
        'strict': False,
        'indexes': [
            ['-is_stocked', 'brand', 'model'],
        ],
    }

The main question is How to include collation in indexes? And will it work with null=True Field?



Solution 1:[1]

class Car(UpdatedAtTimestampMixin, Document):
    model = fields.StringField(null=True, db_field='model')
    brand = fields.StringField(null=True, db_field='brand')
    is_stocked = fields.BooleanField(db_field='isStocked')

    meta = {
        'collection': 'books',
        'strict': False,
        'indexes': [
            {'fields': ['-is_stocked', 'brand', 'model'], 'collation': collation},
        ],
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Antony