Uploaded image for project: 'Node.js Driver'
  1. Node.js Driver
  2. NODE-3173

sort behaves differently when passed as an option or called as a method on cursor

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Major - P3 Major - P3
    • 3.6.7
    • Affects Version/s: 3.6.4
    • Component/s: None
    • Labels:
    • 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

            Assignee:
            daria.pardue@mongodb.com Daria Pardue
            Reporter:
            sergey.petushkov@mongodb.com Sergey Petushkov
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: