[SERVER-35477] Sort by array field doesn't work Created: 07/Jun/18 Updated: 23/Jul/18 Resolved: 08/Jun/18 |
|
| Status: | Closed |
| Project: | Core Server |
| Component/s: | Aggregation Framework, Querying |
| Affects Version/s: | None |
| Fix Version/s: | None |
| Type: | Bug | Priority: | Major - P3 |
| Reporter: | ayamnikov | Assignee: | Nick Brewer |
| Resolution: | Done | Votes: | 0 |
| Labels: | None | ||
| Remaining Estimate: | Not Specified | ||
| Time Spent: | Not Specified | ||
| Original Estimate: | Not Specified | ||
| Issue Links: |
|
||||||||
| Operating System: | ALL | ||||||||
| Participants: | |||||||||
| Description |
|
First case
Meanwhile desc sort works well:
Second case Cursor sort asc works wrong:
Cursor sort desc works right:
Aggregation sort asc works right:
Aggregation sort desc works right:
|
| Comments |
| Comment by ayamnikov [ 08/Jun/18 ] | ||||||||
|
Hi Nick, Thank you for explanation. But I have a question. Don't you think this is a little bit weird semantics for comparison operator? Does it have any practical sense? I've never met this semantics before. I have some production code which relies on the comparison where i-th element of one array compares to i-th element of other, like in strings comparison. And it just worked until I updated MongoDB. I'm using sorting to order documents by 2-tuple key of the format
and I want to use here element-by-element comparison. I believe this is the default array comparison semantics in most languages and libraries. JavaScript (node.js):
Python:
Even PostgreSQL uses element-by-element array comparison: https://www.postgresql.org/docs/9.1/static/functions-array.html Regards, Andrey | ||||||||
| Comment by Nick Brewer [ 07/Jun/18 ] | ||||||||
|
Hi Andrey, The behavior you're seeing in both cases is expected. The disparity you're seeing between 3.4.6 and 3.6.5 is the result of a change made in 3.5.11, where the sort semantics were updated to address the issue of find and aggregate returning different results. The full details of that change have been added as an issue link. When you perform an ascending sort in 3.5.11 and above, the lowest-valued element of the array is used to order the results that are returned. In the case of your first query:
The lowest-valued element is 1. This is due the fact that numbers are a lower BSON type within the comparison order that is used to sort results: https://docs.mongodb.com/manual/reference/operator/aggregation/sort/#sort-pipeline-metadata Conversely, when you perform a descending sort, the highest-valued element of the array is used. In the case of your second query:
The highest-value element is "y", as strings are higher within the comparison order. Regards, Nick
|