简体   繁体   中英

How to get object value with dynamic key in $project in mongoDB

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM