3

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?

0

2 Answers 2

3

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.

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

1 Comment

Suppose you need to practice unwind and group, then mongoplayground.net/p/K82gDoCfF3E this will help you. Before that please refer docs.mongodb.com/manual/reference/operator/aggregation/group
3

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

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.