1

I have this simplex array example in stage

equipaments: [
  {id: 1, number: 1029393, card: 12333},
  {id: 2, number: 1029394, card: 12334},
  {id: 3, number: 1029395, card: 12335}
]

I would like to get this output in the project

['1029393-12333', '1029394-12334', '1029395-12335']

I m trying something like this

{$project: {
  'equipaments': {
    $reduce: {
      input: '$eqp',
      initialValue: [],
      in: {
        $concat: ['$$eqp.number', '-', '$$eqp.card']
      }
    }
  }
}}

1 Answer 1

2

In this case, you should use $map instead of $reduce to transform each item in the array. The syntax is very similar:

db.collection.aggregate([
  {
    $project: {
      "equipaments": {
        $map: {
          input: "$equipaments",
          as: "eqp",
          in: {
            $concat: [
              {
                $toString: "$$eqp.number"
              },
              "-",
              {
                $toString: "$$eqp.card"
              }
            ]
          }
        }
      }
    }
  }
])

if number and card are stored as Int/Long/Double, you'll need to convert them in string before. Note that the $toString operator requires MongoDB 4.0

output:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "equipaments": [
      "1029393-12333",
      "1029394-12334",
      "1029395-12335"
    ]
  }
]

try it online: mongoplayground.net/p/u9FrF-OfdDf

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

Comments

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.