Update an index value of an array of a MongoDB document

1

Well, I'd like to know how to update a value of a document that is inside an array. See the document:

> db.alunos.find().pretty()
{
        "_id" : ObjectId("5ba141b186b9fc17121423a1"),
        "nome" : "Diego",
        "cursos" : [
                {
                        "nome" : "Design Responsivo com Twitter Bootstrap",
                        "cargaHoraria" : 80
                },
                {
                        "nome" : "NodeJS",
                        "cargaHoraria" : 100
                }
        ]
}

I need to update the loadTour of course with name NodeJS. In case it has the hour load of 100h. I would like to update only this course for the 120 hour workload.

    
asked by anonymous 18.09.2018 / 20:27

1 answer

1

You can use the $ conditional operator along with $ set of mongodb

db.alunos.update(
    {
      "_id": ObjectId("5ba141b186b9fc17121423a1"),
      "cursos.nome": "NodeJS"
      }, 
    { "$set": { "cursos.$.cargaHoraria": 120 } }
)
    
21.09.2018 / 13:34