1

I have an array of time periods on a mongo document.

it looks something like this

{
   spans: [{from:2016-1-1, to:2016-1-4}, 
           {from:2016-2-1, from:2016-2-4}]
}

I want to spit the first item into two (eg modify the existing element and add a new one) so that it looks like this

{
   spans: [{from:2016-1-1, to:2016-1-2}, 
           {from:2016-1-3, to:2016-1-4}, 
           {from:2016-2-1, from:2016-2-4}]
}

How can I do this in a single operation (I want it to succeed or fail together)?

I have tried doing an addToSet and set on the element but I cant as I get :

Cannot update 'spans' and 'spans.1.from' at the same time

I could do this by replacing the whole array at once but that seems extremely inefficient. I was wondering if there is a better way.

undefined
  • 33,537
  • 22
  • 129
  • 198
  • If you're looking for an atomic operation to do both I think that's not possible because the reason `Mongodb` focuses on atomic operations to do `one` thing only at a time. In any case, looking. – Swagata Prateek Sep 26 '16 at 00:04
  • @SwagataPrateek Yeah I do really want it to be an atomic operation (at least from my applications perspective). Mongo does seem to allow a bundle of updates but only one at a time to a specific tree in the document. – undefined Sep 26 '16 at 00:29
  • Yeah. Same goes for multiple replacements. I would love this to be an atomic operation too. But I don't think it's there yet or I haven't seen yet in the docs pal. – Swagata Prateek Sep 26 '16 at 00:33

0 Answers0