0

Is it possible using Node JS driver for MongoDB (any) to do the following in one statement (e.g. findOneAndUpdate) to either increment 'value' using $inc of the p_h array element matching timestamp: 1478563200000 or insert new element to p_h array with initial 'value' and 'timestamp': 1478563200000?

{    
"_id" : "582372aa7e46c41988b0016c, 
"p_h" : [
    {
        "value" : 10, 
        "timestamp" : 1478563200000, 
    }, 
    {
        "value" : 15, 
        "timestamp" : 1478564200000, 
    }
] 
}
Duke Ace
  • 177
  • 1
  • 12
  • As i know is not possibile, anyway you can force to move in the most frequent scenario in order to avoid to make 2 query most of the time. Basically "$inc the value" if fail, then "$push it if is not present". Is still needed the condition "if not present" in order to have consistence between data. You can read something more here (http://stackoverflow.com/questions/39982066/auto-calculating-fields-in-mongodb?noredirect=1#comment67423929_39982066) – Daniele Tassone Nov 12 '16 at 09:36

1 Answers1

0

No it's not possible in 1 command. When the timestamp is not yet present you need to $push it to the array. When the timestamp is present you can $inc the value

HoefMeistert
  • 1,190
  • 8
  • 17