mongodbshellaggregation-framework

Create array of strings from array of documents in MongoDB


I am trying to unnest an array of documents into an array of strings, using MongoDB shell:

What I have

  {
    "id": 1,
    "instructions": [
      {
        "field": "A"
      },
      {
        "field": "B"
      },
      {
        "field": "C"
      }
    ]
  }

What I want to obtain

{
     "id":1,
     "instructions": ["A", "B", "C"]
}

What I tried

db.collection.aggregate([
  {
    $unwind: "$instructions"
  },
  {
    $project: {
      "_id": 1,
      "id": 1,
      "instruction": "$instructions.text"
    }
  },
  {
    $group: {
      _id: "id",
      $addToSet: {
        instructions: "$instruction"
      }
    }
  }
])

What I obtain

query failed: (Location40234) The field '$addToSet' must be an accumulator object

Do you know what I am missing?


Solution

  • To solve your problem, use the operator $map in your aggregate to move one by one, as shown in this example script:

    db.collection.aggregate([
      {
        "$project": {
          instructions: {
            $map: {
              input: "$instructions",
              in: "$$this.field"
            }
          }
        }
      }
    ])
    

    **You can test this live in Mongo Playground.

    For detailed usage of $map, read the official documentation on Mongodb.