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

Add $objectValueAt Expression

    • Type: Icon: New Feature New Feature
    • Resolution: Duplicate
    • Priority: Icon: Minor - P4 Minor - P4
    • None
    • Affects Version/s: None
    • Component/s: Aggregation Framework
    • None
    • Query

      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.

            Assignee:
            backlog-server-query Backlog - Query Team (Inactive)
            Reporter:
            jeffm24 Jeffrey Mariconda
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated:
              Resolved: