How to update a nested JSON key

I’m trying to update(using $inc) a key that is nested inside another.
This is how the object is structured:

{
    "_id": {
        "$oid": "5a2f7e82cbd73b0c90563556"
    },
    "title": "title of the poll",
    "choices": {
        "first choice": 0,
        "second choice": 0,
        "third choice": 0,
    }
}

For example, to increment “first choice”, I do the following:

db.collection("polls").update(
     { title: "title of the poll" },
     { $inc: {[choice]: 1} }
)

where [choice] is a string containing the choice. But when i do this, it adds another choice of that name outside of ‘choices’ and increments that:

{
    "_id": {
        "$oid": "5a2f7e82cbd73b0c90563556"
    },
    "title": "title of the poll",
    "choices": {
        "first choice": 0,
        "second choice": 0,
        "third choice": 0,
    }
    "first choice": 1
}

also the ‘choice’ to be updated needs to be from a variable. If I do it using their actual names:

db.collection("polls").update(
     { title: "title of the poll" },
     { $inc: {'choices.first choice' : 1} }
)

I don’t have any problems, but that’s not what i need to do.

any thoughts/ideas on how to make it behave properly?

If you’re updating a nested document, I think the only way is to use 'choices.first choice'

How about this?

db.collection('polls').update(
  {title: 'title of the poll'},
  {$inc: {[`choices.${choice}`]: 1}}
);
1 Like

Kevcomedia can be right though

1 Like

I have tried that, but it seems like you cannot interpolate in a mongodb query like you can in javascript.
By the way i have solved it by storing the value for $inc in another object. in this case the object “update”

    var choice = 'choices.' + data.toString();
    var update = {};
    update[choice] = 1;

where “data” is the choice name
then assign that as the value for $inc

     db.collection("polls").update(
           { title: "title of the poll" },
           { $inc: update }
      )
1 Like

Strange, you should be able to directly compute an object key in JS (as of es6). It could be that your environment doesn’t support it (unlikely IMO), or the string/object is simply malformed.

Either way, glad it worked out :slight_smile:

1 Like

yeah that’s what i thought too. thanks!