How to update a nested JSON key

How to update a nested JSON key
0.0 0

#1

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?


#2

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}}
);

#3

Kevcomedia can be right though


#4

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 }
      )

#5

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:


#6

yeah that’s what i thought too. thanks!