Vinicius Spinellis
Vinicius Spinellis

Reputation: 51

Transform array object to simple array mongodb aggregate

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']
      }
    }
  }
}}

Upvotes: 1

Views: 112

Answers (1)

felix
felix

Reputation: 9285

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

Upvotes: 2

Related Questions