1

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!

1
  • I'm not sure but may be you could try $set, $concat and $merge. Commented Oct 12, 2021 at 1:13

1 Answer 1

3

You can use reduce

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

Working Mongo playground

Sign up to request clarification or add additional context in comments.

2 Comments

You can also use $map as follows: mongoplayground.net/p/l5J7U5ddBS8
Yeah, using $map is also a good solution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.