title: How to make a rethinkdb atomic update if document exists, insert otherwise?
body: <p>How to make a rethinkdb atomic update if document exists, insert otherwise?</p>
  
  <p>I want to do something like:
  </p>
  
  <pre class="lang-js prettyprint-override"><code>var tab = r.db('agflow').table('test');
  r.expr([{id: 1, n: 0, x: 11}, {id: 2, n: 0, x: 12}]).forEach(function(row){
    var _id = row('id');
    return r.branch(
      tab.get(_id).eq(null),  // 1
      tab.insert(row),        // 2 
      tab.get(_id).update(function(row2){return {n: row2('n').add(row('n'))}}) // 3
    )})
  </code></pre>
  
  <p>However this is not fully atomic, because between the time when we check if document exists (1) and inserting it (2) some other thread may insert it.</p>
  
  <p>How to make this query atomic? </p>