Accessing a random field using other field value

Viewed 28

I have a document like this:

{
    value: "field2",
    field1: [ ... ],
    field2: [ ... ],
    ...
}

Where value will be the value of one of the fields in the document. and many different fields are possible for one document.

I want to match a document. fetch the relevant field only and them do some calculations on it.

For example I want to do:

{
  $unwind: "$value"
}

And get the results of field2 unwinded. How can I do this?

1 Answers

It's a little bit "hacky" but you can achieve this using operators like $objectToArray and $filter like so:

db.collection.aggregate([
  {
    $addFields: {
      "values": {
        $arrayElemAt: [
          {
            $filter: {
              input: {
                $objectToArray: "$$ROOT"
              },
              as: "field",
              cond: {
                $eq: [
                  "$$field.k",
                  "$value"
                ]
              }
            }
          },
          0
        ]
      }
    }
  },
  {
    $unwind: "$values.v"
  },
  {
    $replaceRoot: {
      newRoot: "$values.v"
    }
  },
  
])

MongoPlayground

Related