mongodbaggregation

Using dynamic path in MongoDB aggregation pipeline with $getField operator


How can I use a dynamic path in my MongoDB aggregation pipeline to assign the value of 'address.city' to a field named 'fieldName' using the $getField operator? The current query I have doesn't seem to be working as expected. Just a little note- I want to keep "fieldName" in order to calculate dynamically the path.

db.collection.aggregate([
  {
    $addFields: {
      fieldName: "address.city",
    }
  },
  {
    $addFields: {
      fieldValue: {
        $getField: {
          field: "$fieldName",
          input: "$$ROOT"
        }
      }
    }
  }
])

Solution

  • Write this as an answer from the comment as it resolves the Post Owner's question.

    Unfortunately, it is not possible to access the value as the field name in the $getField or other operator.

    But what you can achieve is:

    1. Convert the key-value pair to an array of objects consisting of k and v fields via $objectToArray.

    2. Filter the matched object by matching the value of k via the $filter operator.

    3. Convert the array of objects to a key-value pair via $arrayToObjectt.

    {
      $set: {
        linkedStreets: {
          $objectToArray: "$linkedStreets"
        }
      }
    },
    {
      "$project": {
        "fieldValue": {
          $arrayToObject: {
            $filter: {
              input: "$linkedStreets",
              cond: {
                $eq: [
                  "$$this.k",
                  "$$steertType"
                ]
              }
            }
          }
        }
      }
    }
    

    Demo @ Mongo Playground