Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-1739

.first and .last add _id field to sort resulting in index miss

    • Type: Icon: Task Task
    • Resolution: Done
    • 12_01_17
    • Affects Version/s: None
    • Component/s: None
    • Labels:
      None

      When you call .first on a criteria object it adds the ID field at the end of the sort. This results in, unexpected, index misses.

      I expect:

      Collection.where(:field_a=>"some_value").desc(:field_b)

      to result in the query:

      db.collection.find(

      {field_a: "some_value"}

      ).sort(

      {field_b:-1}

      )

      This means a compound index on field_a, field_b will actually work.

      But if you do:

      Collection.where(:field_a=>"some_value").desc(:field_b).first

      this actually results in:

      db.collection.find(

      {field_a: "some_value"}

      ).sort(

      {field_b:-1, _id:1}

      )

      I guess mongo should actually still use the index, but it doesn't.

      Possible solution:

      Add limit(1) to the query, return the result(s) and then call first item of the array.

            Assignee:
            Unassigned Unassigned
            Reporter:
            olery Olery
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: