title: Auto-increment in Native MongoDB
body: <p>Yeah, You might get here thinking "this is rather a duplicated question", it might be indeed, but after about a couple hours searching for the answer of the problem, I fail to find one single answer that actually solve my problems, and to be honest most of the people that asked the same thing. So I'm gonna try to make a different question, so here it goes. </p>
  
  <p>Has anyone actually manage to port the function below described in the mongo doco into the mongodb native driver? I'm using nodejs and I'm having a hard time trying to port this to it's native driver. </p>
  
  <pre><code>function insertDocument(doc, targetCollection) {
  
      while (1) {
  
          var cursor = targetCollection.find( {}, { _id: 1 } ).sort( { _id: -1 } ).limit(1);
  
          var seq = cursor.hasNext() ? cursor.next()._id + 1 : 1;
  
          doc._id = seq;
  
          targetCollection.insert(doc);
  
          var err = db.getLastErrorObj();
  
          if( err &amp;&amp; err.code ) {
              if( err.code == 11000 /* dup key */ )
                  continue;
              else
                  print( "unexpected error inserting data: " + tojson( err ) );
          }
  
          break;
      }
  }
  </code></pre>
  
  <p>I read about the nextObject(), toArray(), forEach() and etc. but still can't successfully port it. </p>
  
  <p>Has anyone actually managed to make this happened with this function? I'm looking for the real answer, I know a lot of people might be also interested.</p>
  
  <p>I'm asking this one in particular, because from my understanding this one is the most "safe" one to use as the other suggestions has some flaws when trying to insert multiple documents at the same time.</p>
  
  <p>And no, this is not for my unique id, i'm still using the ObjectID, i just need a serial number, that will be unique for every record.</p>
  
  <p>If you have done it, please share!!! you will save me a loooootttt of time! :)</p>
  
  <p>thanks</p>