Search code examples
arraysmongodbelement

How to add new field to Array element in MongoDB?


I need add new field to Array element in MongoDB, this is my collection:

doc1={
    "Name":"Dat",
    "Academic level":[
            {
            "Primary school": "Binh Tri 2",
            "Classification":"A"
            },
            {
            "Junior high school": "Binh Tri Dong",
            "Classification":"B"
            },
            {
            "High school": "Mac Dinh Chi",
            "Classification":"C"
            },
    ]
}

I want to add "Achievement" for all Array element, example:

doc1={
    "Name":"Dat",
    "Academic level":[
            {
            "Primary school": "Binh Tri 2",
            "Classification":"A",
            "Achievement":true
            },
            {
            "Junior high school": "Binh Tri Dong",
            "Classification":"B",
            "Achievement":true
            },
            {
            "High school": "Mac Dinh Chi",
            "Classification":"C",
            "Achievement":true
            },
    ]
}

I tried many solutions on the internet but it didn't work, please help me, thank you very much


Solution

  • Simply $set the field in an update with aggregation pipeline.

    db.collection.update({},
    [
      {
        $set: {
          "Academic level.Achievement": true
        }
      }
    ],
    {
      multi: true
    })
    

    Mongo Playground