Update of an index of an array of a Mongodb document

Asked

Viewed 107 times

1

Guys, I would like to know how to update a document value 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 carHoraria of the course named Nodejs. In the case is with the workload of 100h. I would like to update only this course for the 120h workload.

1 answer

1


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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.