Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Case insensitive sorting on multiple field #111

Closed
terravi opened this issue Sep 8, 2021 · 3 comments
Closed

Case insensitive sorting on multiple field #111

terravi opened this issue Sep 8, 2021 · 3 comments

Comments

@terravi
Copy link

terravi commented Sep 8, 2021

I need to be able to sort documents by multiple fields in case insensitive mode. In mongo db I could do this with collations and strength at 1. I have not found a way to use collations with beanie.

@terravi
Copy link
Author

terravi commented Sep 8, 2021

I have solved deriving FindMany in my project and overriding the motor_cursor property in order to pass the collation parameter to the find method of the AsyncIOMotorCollection motor class

class CustomFindMany(FindMany):
def init(self, instance: FindMany):
self.parent = instance
self.collation_expressions = None

def collation(self, collation):
    if collation is not None:
        self.collation_expressions = collation
    return self

def __getattr__(self, name):
    return getattr(self.parent, name)

@property
def motor_cursor(self):
    return self.document_model.get_motor_collection().find(
        filter=self.get_filter_query(),
        sort=self.sort_expressions,
        projection=get_projection(self.projection_model),
        skip=self.skip_number,
        limit=self.limit_number,
        collation=self.collation_expressions,
        session=self.session,
    )

@terravi terravi closed this as completed Sep 8, 2021
@roman-right
Copy link
Member

Hey @terravi ,

Thank you for the input. It looks like an important feature. I'll add this to Beanie soon.

@hosamk92
Copy link

I faced this earlier couldn't find docs on how to achieve it, but it can be achieved now just by adding the collation param to the find function:

model_type.find(
            query,
            collation={"locale": "en", "strength": 2}  # handle case-insensitive sorts
        ).sort((field, sort_order)).to_list()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants