Skip to content
Advertisement

Mongodb Insert dynamic unique keys to nested object add if not exist else update

I need to operate something same as how $addtoset works for arrays in mongodb but for an object,Im adding dynamically generated objects to an object. The dynamic key is based on a string which will help to maintain a unique value so another key will not inserted with the same dynamic key.

i tried $set which actually updates

JavaScript

This is the result i prefer,

JavaScript

If the object key exists update, if not insert a new key. This is how i achieved for an array,

JavaScript

Now i need your help to achieve this for an object. Thank You!

Advertisement

Answer

You’re very close to the solution, just need a little change:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement