Uploaded image for project: 'Documentation'
  1. Documentation
  2. DOCS-1111

Misleading/ambiguous statement in the index page regarding sort and query

    • Type: Icon: Task Task
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • v1.2
    • Affects Version/s: None
    • Component/s: None
    • Labels:
      None

      The Indexing Strategies page (http://docs.mongodb.org/manual/applications/indexes/#use-indexes-to-sort-query-results) has the following statement:

      For queries that include a sort that uses a compound index, ensure that all fields before the first sorted field are equality matches.

      I verified with Aaron to decode the sentence as such:

      For queries that include a sort that uses a compound index, if the sortuses a subset of the index, such as .sort(

      { b: 1 }

      ), then to ensure
      that MongoDB uses the index both to retrieve and sort, the query should use equality conditions for those index fields that precede the
      sort index field.

      So, for an index of

      { a: 1, b: 1, c:1, d: 1 }
      • If we have a query with .sort( { b: 1 }

        ), the preceding index field 'a' should be included in the query with an equality condition:

      db.collection.find(

      { a: 5 }

      ).sort(

      {b:1 }

      )

      • If the query condition on the preceding index field is not an equality
        condition, MongoDB may sort the documents after it retrieves them
        from an index (i.e. the scanAndOrder: true)

      db.collection.find( { a: {$gt: 5} } ).sort(

      { b:1 }

      )

      As for the query you were specifically wondering about:

      db.collection.find(

      { b:5 }

      ).sort(

      { a:1, b:1 }

      )

      that query uses a subset in the .sort(); however, the first index field in the sort keys is 'a' and in our index of

      { a: 1, b: 1, c:1, d: 1 }

      , there is no field
      preceding 'a'; so it does not need to be part of the query condition.

            Assignee:
            kay.kim@mongodb.com Kay Kim (Inactive)
            Reporter:
            kay.kim@mongodb.com Kay Kim (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved:
              10 years, 39 weeks, 4 days ago