Skip to content
Advertisement

change only one field of entire array of embedded document in mongoose

i have a list schema and a question set schema. the quetsionSet schema is embedded inside the list schema. its working fine but how can i update anything inside the array of embedded document i.e. here i want to change the listname of all the documents inside questionSet (array of questionSet documents).

here is an example of my list document model

{ "_id" : ObjectId("60f2cc07275bbb30d8cb268e"), 
"listName" : "dsa", 
"aboutList" : "dsa queestions",
 questionSet" : [ { "solved" : false, 
                   "_id" : ObjectId("60f2cc12275bbb30d8cb2695"), 
                    "topic" : "array", 
                     "name" : "array is best", 
                    "url" : "www.arr.com", 
                       "listname" : "dsa", 
                     "__v" : 0 }, 
               { "solved" : false,  
                 "_id" : ObjectId("60f2cc1b275bbb30d8cb269d"), 
                "topic" : "linked list",
               "name" : "reverse list", 
                 "url" : "www.list.com",
                "listname" : "dsa",
                 "__v" : 0 } 
               ], 
"__v" : 2 
}

Advertisement

Answer

you can use the following in your case

db.<collection_name>.updateOne(
    {   "_id" : ObjectId("60f2cc07275bbb30d8cb268e")},
    {
      $set: {
        'questionSet.$[].listname': "javascript"
      }
    } 
  )
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement