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?

Upvotes: 3

Views: 721

Answers (2)

matthPen
matthPen

Reputation: 4363

Another approach to solving the problems if you no need to use $map, you simply edit project your field like below:

db.collection.aggregate([
  {
    "$project": {
      instructions: "$instructions.field"
    }
  }
])

Live test in Mongo Playground click here

Upvotes: 3

varman
varman

Reputation: 8894

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.

Upvotes: 3

Related Questions