1

I have a document with a nested array array_field:

{
  "_id": {
    "$oid": "1"
  },
  "id": "1",
  "array_field": [
    {
      "data": [
        {
          "regions": [
            {
              "result": {
                "item": [
                  "4",
                  "5",
                  "3"
                ]
              }
            },
            {
              "result": {
                "item": [
                  "5"
                ]
              }
            },
            {
              "result": {
                "item": [
                  "1"
                ]
              }
            }
          ]
        }
      ]
    }
  ]
}

I need add new field, new_added_field for example, with each array element from array_field.data.regions.result.item and remove array_field from document.

For example:

{
  "_id": {
    "$oid": "1"
  },
  "id": "1",
  "new_added_field": [4,5,3,5,1]
}

I think i can do this with help of $unwind or $map but have difficulties and need dome hint, how i can do it with help op aggregation?

1 Answer 1

1

As you said,

db.collection.aggregate([
  {
    "$project": {
      newField: {
        "$map": {
          "input": "$array_field",
          "as": "m",
          "in": "$$m.data.regions.result.item"
        }
      }
    },
    
  },
  { "$unwind": "$newField" },
  { "$unwind": "$newField" },
  { "$unwind": "$newField" },
  { "$unwind": "$newField" },
  {
    "$group": {
      "_id": "$_id",
      "newField": { "$push": "$newField" }
    }
  }
])

Working Mongo playground

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

1 Comment

Instead of unwind and group you can $reduce

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.