-
Type: New Feature
-
Resolution: Duplicate
-
Priority: 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.
- duplicates
-
SERVER-30417 add expression to get value by keyname from object
- Closed