Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-19507

Distinct command should use covered query plan when distinct field is a non-first element of index key pattern

    • Type: Icon: Improvement Improvement
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 3.3.12
    • Affects Version/s: None
    • Component/s: Querying
    • None
    • Fully Compatible
    • Query 2016-08-29

      Compound indexes should be able to support covered distinct queries, where the distinct key is a non-first element of the index key pattern. Distinct queries are able to use these indexes, but only non-covered plans are generated.

      Reproduce with the following:

      > var l = db.setLogLevel(5,'query')
      > db.foo.drop()
      true
      > db.foo.ensureIndex({a:1,b:1})
      {
      	"createdCollectionAutomatically" : true,
      	"numIndexesBefore" : 1,
      	"numIndexesAfter" : 2,
      	"ok" : 1
      }
      > db.foo.distinct("b",{a:1}) // Should use covered plan on {a:1,b:1}.
      

      From the verbose query log output below, it can be seen that a FETCH <= IXSCAN plan is generated. The FETCH stage here is unnecessary, as the index already contains all information needed in order to generate the set of distinct keys for the requested field.

      2015-07-21T13:50:57.081-0400 D QUERY    [conn4] Planner: adding solution:
      FETCH
      ---fetched = 1
      ---sortedByDiskLoc = 0
      ---getSort = [{ a: 1 }, { a: 1, b: 1 }, { b: 1 }, ]
      ---Child:
      ------IXSCAN
      ---------keyPattern = { a: 1.0, b: 1.0 }
      ---------direction = 1
      ---------bounds = field #0['a']: [1.0, 1.0], field #1['b']: [MinKey, MaxKey]
      ---------fetched = 0
      ---------sortedByDiskLoc = 0
      ---------getSort = [{ a: 1 }, { a: 1, b: 1 }, { b: 1 }, ]
      

            Assignee:
            david.storch@mongodb.com David Storch
            Reporter:
            rassi J Rassi
            Votes:
            14 Vote for this issue
            Watchers:
            20 Start watching this issue

              Created:
              Updated:
              Resolved: