-
Type: Bug
-
Resolution: Fixed
-
Priority: Major - P3
-
Affects Version/s: 3.6.4
-
Component/s: None
-
Empty show more show less
-
Not Needed
When using array value for sort to preserve the sort order for numeric key values it works fine when sort is called on a cursor returned by find call. When the same sort value is provided as an option to the find method, the sort order is not preserved.
To reproduce you can create a small collection with a few numeric keys:
> await client.db('test').collection('coll').insertMany([{ '1': 1 }, { '2': 1 }, { '3': 1 }])
... and then try to sort them using different methods. Using .sort() works as expected:
> await client.db('test').collection('coll2').find({}).sort([['3', -1], ['1', -1]]).toArray() [ { '3': 1, _id: 605cacd1a5b7d77dce3b4b25 }, { '1': 1, _id: 605cacc4a5b7d77dce3b4b23 }, { '2': 1, _id: 605cacc8a5b7d77dce3b4b24 } ]
But passing sort as an option to find produces a different result:
> await client.db('test').collection('coll2').find({}, {sort: [['3', -1], ['1', -1]]}).toArray() [ { '1': 1, _id: 605cacc4a5b7d77dce3b4b23 }, { '3': 1, _id: 605cacd1a5b7d77dce3b4b25 }, { '2': 1, _id: 605cacc8a5b7d77dce3b4b24 } ]
The culprit seems to be in a different way of handing sort argument for cursor method and the find option. In find method the sort option is converted back to the object from array and as such looses the ordering, sort method converts an array to a Map and as such, the sort order is preserved when passed to the server
- is related to
-
NODE-3174 Driver 4 doesn't preserve the sort key order
- Closed
- related to
-
COMPASS-4258 Sort does not preserve field order
- Closed
-
NODE-578 Order of sort fields is lost for numeric field names
- Closed