Home > front end >  MongoDB. Get every element from array in new field
MongoDB. Get every element from array in new field

Time:05-19

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?

CodePudding user response:

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

  • Related