title: Upserts in mongodb when using custom _id values
body: <p>I need to insert a document if it doesn't exist. I know that the "upsert" option can do that, but I have some particular needs.</p>
  
  <p>First I need to create the document with its _id field only, but only if it doesn't exist already. My _id field is a number generated by me (not an ObjectId). If I use the "upsert" option then I get "Mod on _id not allowed"</p>
  
  <pre><code>db.mycollection.update({ _id: id }, { _id: id }, { upsert: true });
  </code></pre>
  
  <p>I know that we can't use the _id in a $set. </p>
  
  <p>So, my question is: If there any way to a "create if doesn't exists" atomically in mongodb?</p>
  
  <p>EDIT:
  As proposed by @Barrie this works (using nodejs and mongoose):</p>
  
  <pre><code>var newUser = new User({ _id: id });
  newUser.save(function (err) {               
      if (err &amp;&amp; err.code === 11000) {            
              console.log('If duplicate key the user already exists', newTwitterUser);
          return;
      }
      console.log('New user or err', newTwitterUser);
  });
  </code></pre>
  
  <p>But I still wonder if it is the best way to do it.</p>