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?