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

const update = { 
    $set: { 
      'resources.defs.icons': {
        [md5(iconURL)]: {
          persist: persist,
          iconURL: iconURL,
          iconName: _.get(iconData, 'iconName')
        }
      }
    }
  };

This is the result i prefer,

 "resources": {
  "defs": {
    "icons": {
      "c1b79846875970da7ee9cc5b1f9cc4ad": {
        "persist": true,
        "iconURL": "URL",
        "iconName": ""
      }
    },
    {
      "28b569d3f9a3e63f94ca6fad969475f9": {
        "persist": true,
        "iconURL": "imageUrl",
        "iconName": ""
      }
    }
  }
}

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

 const update = { 
    $addToSet: { 
      'resources.defs.icons': {
        [md5(iconURL)]: {
          persist: persist,
          iconURL: iconURL,
          iconName: _.get(iconData, 'iconName')
        }
      }
    }
  };

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:

const update = { 
  $set: { 
    [`resources.defs.icons.${md5(iconURL)}`]: {
      persist: persist,
      iconURL: iconURL,
      iconName: _.get(iconData, 'iconName')
    }
  }
};
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement