Answer the question
In order to leave comments, you need to log in
How can I dynamically pick up a mongodb key?
There is an object in the database obj = {key1:{}, key2:{}}
It is necessary to update the 1st of the keys in the database depending on the value recorded in a separate place (obj2.key = 'key2';).
So the problem is that if I write:
collection.update({name:user}, {$set:{'obj[obj2.key]':JSON.parse(info)}} does not write to the obj.key2 field what I tried to manipulate this part of 'obj[obj2.key]' but it didn't work. Tell me how you can dynamically select the key.
PS: I'm just starting with mongo, I didn't find an answer to the question, or else my request was incorrectly composed :)
Thank you in advance.
Answer the question
In order to leave comments, you need to log in
You cannot use the values of the current document in $set to calculate values or keys. You will first need to read obj2, extract the key from there and substitute its value in $set.
I tried to do something like this
var a = 'obj['+ obj2.key+ ']' or 'obj.'+obj2.key
$set:{a:something}
though then it writes a key named a to the database
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question