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

Add $objectValueAt Expression

    XMLWordPrintable

    Details

    • Type: New Feature
    • Status: Closed
    • Priority: Minor - P4
    • Resolution: Duplicate
    • Affects Version/s: None
    • Fix Version/s: None
    • Component/s: Aggregation Framework
    • Labels:
      None

      Description

      There is currently no object analog to the $arrayElemAt expression that would allow you to easily access an object value at a variable key returned by an expression. Because of this, the most direct way to achieve this in a single step is to do the following:

      {
          $addFields: {
              valueAtKey: {
                  $let: {
                      vars: { keyVals: { $objectToArray: '$someObjectField' } },
                      in: {
                          $arrayElemAt: [
                              '$$keyVals',
                               { $indexOfArray: ['$$keyVals.k', '$someKeyField'] }
                          ]
                      }
                  }
              }
          }
      }

      This seems really roundabout and, on top of that, it actually returns the { k: ..., v: ... } object, so either another nested $let or a following $addFields stage would be needed if you just wanted the value.

       

      It would be much more ideal, if possible, to be able to do something similar syntax-wise to $arrayElemAt like the following:

      {
          $addFields: {
              valueAtKey: { $objectValueAt: ['$someObjectField', '$someKeyField'] }
          }
      }

      This would, ideally, resolve directly to the value if found and null otherwise. There would probably also need to be an error case, similar to $arrayElemAt, when the second argument does not resolve to a string.

        Attachments

          Issue Links

            Activity

              People

              • Votes:
                0 Vote for this issue
                Watchers:
                6 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved: