Mongo Array Update

Hey Guys,

Having a problem with updating an array value in my mongodb. I have the following schema set up, which is very simple. The schema is for a questionnaire/survey app I’m building.

{
"_id" : "wq6ZEkPnSpHsLQ6Kd",
"completion" : false,
"vendorId" : "jgKaDi24qqfWP6nQq",
"clientId" : "QqFoc8b2Mcu7bx7mm",
"result" : [ 
    {
        "question029" : "fdsfa",
        "sectionName" : "section029"
    }
],
"status" : "unlocked"
}

That’s it. Now I’m trying to update the “myAnswer” field to reflect the new input supplied. However I CANNOT seem to get my query right. I’ve ran into a ton of errors using $set, $addToSet, $unset, etc. I need to change “question029” to whatever the new input is, as stated before. The tricky part is that they key itself (question029) is dynamically created. You name it I’ve tried it. I know I’m missing something small and could really use some help. I’ve been on this longer than I care to admit.

Thanks guys :slight_smile:

You want to change the key “question029” or the value of “question029”?
If it’s the value, this should work:

db.questions.update(
   { _id: "wq6ZEkPnSpHsLQ6Kd", "result.sectionName": "section029"},
   { $set: { "result.$.question029" : "This is tha new value yo" } }
)

You are an absolute genius my friend. Seriously you’ve saved me an all-nighter. I honestly couldn’t thank you enough. I’ve gotta demo this to a client tomorrow and I was freaking out!!

Thanks man!!!

Glad to help. Tell the client to send me the beers :wink:

1 Like