A
A
Artcl2014-03-09 22:13:38
MongoDB
Artcl, 2014-03-09 22:13:38

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

3 answer(s)
_
_ _, 2014-03-10
@AMar4enko

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.

A
Artcl, 2014-03-10
@Artcl

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

M
mr null, 2014-04-12
@mr_null

obj can be picked up, since the name is some kind of hash with a serial number.
write 1 obj followed immediately by 2 obj. the difference in the name will be small.
here it is necessary to read the documentation on what principle a hash is created.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question