Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 230
Sergi Justiniano Claramunt Avatar asked Dec 06 '25 10:12

Sergi Justiniano Claramunt


1 Answers

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.

like image 135
varman Avatar answered Dec 08 '25 23:12

varman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!