Home > Net >  Concat strings in nested json with other string in MongoDB
Concat strings in nested json with other string in MongoDB

Time:10-12

I am trying an aggregation in MongoDB in order to convert:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "acronym": "MC",
    "tickers": [
      {
        "name": "Sensor1-front",
        "symbol": "s1f"
      },
      {
        "name": "Sensor1-back",
        "symbol": "s1b"
      }
    ]
  }
]

into something like this:

['s1f.MC','s1b.MC']

Where each symbol in tickers is concat to acronym.

I am trying it with $concat, $group, etc but I am not going anywhere.

Thanks!

CodePudding user response:

You can use reduce

db.collection.aggregate([
  {
    $addFields: {
      newField: {
        "$reduce": {
          "input": "$tickers",
          "initialValue": [],
          "in": {
            "$concatArrays": [
              [
                {
                  "$concat": [
                    "$$this.symbol",
                    ".",
                    "$acronym"
                  ]
                }
              ],
              "$$value"
            ]
          }
        }
      }
    }
  }
])

Working Mongo playground

  • Related