MongoEngine/mongoengine

Sorting on nested field that contains `__` in its name.

ws903 opened this issue · 1 comments

If I run a query like .objects().order_by('-response.Funding_custom__c'), explain tells me that sortPattern is
'sortPattern': {'response.Funding_custom.c': -1}.

How should I ensure that Funding_custom__c is recognized as a single field?

MongoEngine uses "__" internally as a way of expressing nested fields in the query language (as dots can't be used in keyword arguments originally) so this is clearly what clashes. Changing that and starting to support double underscores everywhere is not something that can be easily changed but as a workaround, I've just added a __raw__ keyword argument to order_by. This is simple to implement and is consistent with other places where __raw__ can be used (e.g in Document.objects(__raw__={...}))

That being said, if you have the option, you should avoid the double underscores entirely in your keys if you plan to use Mongoengine more broadly, otherwise it's just a question of time before you run into other issues