motormal
motormal

Reputation: 178

MongoDB dynamic subfield name

I have a document like:

{
  idx: {a: 1, b: 2, c: 3},
  v: "a"
}

In an aggregation query, I'd like to add a field x to the doc by taking the value of v and using it to find the corresponding value in idx. The resulting doc would look like:

{
  idx: {a: 1, b: 2, c: 3},
  v: "a",
  x: 1
}

I've tried things like $addFields: {x: "$idx.$a"} and $addFields: {x: "$idx[$a]"} but these are not working. I've scanned the list of pipeline operators but I don't see any that would help. Is this possible?

Upvotes: 2

Views: 119

Answers (1)

mickl
mickl

Reputation: 49945

There's no easy way but you can take advantage of $objectToArray operator to get idx as an array of keys and values and then use $filter with $arrayElemAt to get matching element.

db.collection.aggregate([
        {
            $addFields: {
                x: {
                    $let: {
                        vars: {
                            match: {
                                $arrayElemAt: [
                                    { $filter: { input: { $objectToArray: "$idx" }, cond: { $eq: [ "$$this.k", "$v" ] } } },
                                    0
                                ]
                            }
                        },
                        in: "$$match.v"
                    }
                }
            }
        }
    ])

Mongo Playground

Upvotes: 1

Related Questions