1

I want to retrieve a value from an object with a dynamic key

[
  {
    "_id": 1,
    "item": "sweatshirt",
    "price": {
      "INR": 45.99
    },
     "currency": 'INR'
  }
]


db.collection.aggregate([
  {
    "$project": {
      "pricenew": "$price.currency"
    }
  }
])

If I do price.INR it will work fine but here I have currency dynamic, so I want something like price.currency but here currency is coming like "INR" and it gives no data.

I really appreciate any help you can provide.

Sohan
  • 558
  • 6
  • 17
  • `obj.price[obj.currency]` –  Aug 22 '22 at 10:47
  • Duplicate [How can I access and process nested objects, arrays, or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) –  Aug 22 '22 at 10:48
  • @ChrisG I am trying to do it in $project aggregation and not in just javascript. – Sohan Aug 22 '22 at 10:52

1 Answers1

0

You need to convert the price object to an array using $objectToArray, filter it and then convert it back, like so:

db.collection.aggregate([
  {
    $replaceRoot: {
      newRoot: {
        "$mergeObjects": [
          {
            "$arrayToObject": {
              $map: {
                input: {
                  $filter: {
                    input: {
                      "$objectToArray": "$price"
                    },
                    cond: {
                      $eq: [
                        "$$this.k",
                        "$currency"
                      ]
                    }
                  }
                },
                in: {
                  k: "pricenew",
                  v: "$$this.v"
                }
              }
            }
          },
          {
            _id: "$_id"
          }
        ]
      }
    }
  }
])

Mongo Playground

Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43