官方提供了两种方法 Use Counters Collection 和 Optimistic Loop, 以 _id 为例来说明下这两种方法.
[TOC]
Use Counters Collection
1. Insert into the counters collection, the initial value for the userid:
db.counters.insert( { _id:"userid", seq:0 })
2. Create a getNextSequence function that accepts a name of the sequence. The function uses the findAndModify() method to atomically increment the seq value and return this new value:
1. Create a function named insertDocument that performs the "insert if not present" loop. The function wraps the insert() method and takes a doc and a targetCollection arguments.