0

I have a document structure like so:

{   
  data: null,
  subArray: [{
    key: 'a',
    subData: [] 
  }, {
    key: 'b',
    subData: []
  }] 
}

I will receive an array containing subArray keys, like: `['a', 'b']

I want to iterate over the subArray to push a value to subData, so that when subArray is ['a','b'], my data will now be like:

{   
  data: null,
  subArray: [{
    key: 'a',
    subData: ['dataToPush'] 
  }, {
    key: 'b',
    subData: ['dataToPush']
  }] 
}

I have this query to do that:

update({_id:"...", "subArray.key":{"$in":['a','b']},
       {'$addToSet':{'subArray.$.subData':'...'}}})

Thinking that $in will let me loop through my subArray. But I realize this does not work because $in gets the elements that match the elements in the array, so I will get my data but not iterate over my subArray.

Is it possible to complete this with a specific selector/modifier combo?

1 Answer 1

1

No, not with multiple keys. For one key "a", you could use a query like

db.test.update({ "subArray.key" : "a" }, { "$push" : { "subArray.$.subData" : "dataToPush" } })

but the $ positional operator can only be used for a single match in one update. You could do one update like the above per key, or retrieve the document, modify it based on all of the keys, then save over the original.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.