0

I'm trying to target a object in an array, then insert data in that same object, beside the matched key/value pair. Here is an example:

profile = [
   {
      data: 'value',
      array: [
         'one',
         'three'
      ]
   }
]

var i = 0;
var selector = 0;
_.each(profile, function(elem) {
    if (elem.data === 'value') {
        selector = i;
    }
    i++
}
profile[selector].array.push('two');

This is a workaround to add to an array of objects/arrays, but I'm trying to find a way to do this with Meteor MongoDB. Is there a selector that will enable me to target the appropriate array (with matching key/value pair) then target the "array" beside it and push something to it?

1 Answers1

1

Assuming you have stored an object in mongodb that looks like this

{
    profile : [
        {
            data: 'value',
            array: [
                'one',
                'three'
            ]
        }
    ]
}

I was able to use this in mongodb shell.

db.yourCollection.update(
    {"profile.data":"value"},
    {"$push":
        {
            "profile.$.array":"two"
        }
    }
);

This finds the record where the profile property data equals "value" and pushes "two" to the property array.

Reference: Mongodb $push in nested array

Community
  • 1
  • 1