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

Provide way to specify field order in $project or use field order listed in project spec

      There've been requests for preserving field order that $project gives, i.e. if it specifies field3:1, field1:1, newField:{something}, field0:1 then it's desired for the fields to be in that specific order in the result.

      Original summary:
      $project doesn't swap order of embedded fields if the fields have the same name as in the original document

      Original Description:
      3.0.1

      Best explained by example:

      db.test.drop()
      db.test.insert({ "a" : { "x" : 1, "y" : 2 } })
      // expectation is that this will swap the order of the fields in the embedded object, producing
      // { "a" : { "y" : 2, "x" : 1 } }
      db.test.aggregate([{ "$project" : { "a" : { "y" : "$a.y", "x" : "$a.x" } } }])
      { "a" : { "x" : 1, "y" : 2 } }
      // the order is swapped if you change the name of the fields
      db.test.aggregate([{ "$project" : { "a" : { "_y" : "$a.y", "_x" : "$a.x" } } }])
      { "a" : { "_y" : 2, "_x" : 1 } }
      

      Simple workaround is to swap fields by rename them in the projection, then renaming the fields back to their original names in another project, but still this seems like incorrect behavior because the order of keys in an embedded object is meaningful.

            Assignee:
            asya.kamsky@mongodb.com Asya Kamsky
            Reporter:
            william.berkeley William Berkeley
            Votes:
            15 Vote for this issue
            Watchers:
            21 Start watching this issue

              Created:
              Updated:
              Resolved: