I have an issue with indexing and sorting of fields with unknown type in my use case. This means they may be an Array in one document, but the same field in another document could be something else.
Now, you may know Mongo doesn’t allow indexing or sorting on multiple Array fields it gives the following error if you try : “cannot sort with keys that are parallel arrays”
As an exemple to explain this post I’ll use the following index : {a:1,b:1}
Keep in mind field a and field b can be of any type in this exemple (Object, Array, number, string, Date etc…) and the type can be different between documents.
In this exemple if I try to insert the following document it works :
{a:1, b:2}
{a:[1,2,3],b:"hi"}
But if I try to insert a document like this :
{a:[1,2,3], b:["a","b","c"]}
I get an error.
I don’t know what to do to fix this issue, and this restriction makes no sense.
https://jira.mongodb.org/browse/SERVER-826
I absolutely need in my use case to be able to sort on arbitrary fields, and I’ve yet to come up with a workaround that makes sense and won’t impact performance too much.
The workaround I came up with :
-
Create a copy of all fields for sorting purposes where Arrays are converted to strings or another format (Obviously this is very bad because it duplicates all data)
1.exemple :{a:1, a_sort:1, b:[1,2,3], b_sort:"[1,2,3]"}and the index :{a_sort:1, b_sort:1} -
Replace the $sort aggregation stage with a $function aggregation performing a custom sort, this is also very bad because we lose all benefits from indexes and the optimization on the $limit stage (limit stage optimization can be somewhat emulated in the function by returning immediatly false in the filter, but it won’t be as efficient as the mongo one)
Are there other workarounds I haven’t though of ? Will the Mongo Team ever give us an option to bypass this limitation since from what I can tell it’s only meant to stupid proof against very inefficient sorts ? But in my case my workarounds would certainly result in worse performances than what I could get from a regular sort.
Any help is appreciated