You'll need to use MongoDB's findAndModify command. With it, you can atomically select and increment a field.
db.seq.findAndModify({
query: {"_id": "users"},
update: {$inc: {"seq":1}},
new: true
});
This will increment a counter for the users
collection, which you can then add to the document prior to insertion. Since it's atomic, you don't have to worry about race conditions resulting in conflicting IDs.
It's not as seamless as MySQL's auto_increment
flag, but you also usually have the option of specifying your own ID factory in your Mongo driver, so you could implement a factory that uses findAndModify to increment and return IDs transparently, resulting in a much more MySQL-like experience.
The downside of this approach is that since every insert is dependent on a write lock on your sequence collection, if you're doing a lot of writes, you could end up bottlenecking on that pretty quickly. If you just want to guarantee that documents in a collection are sorted in insertion order, then look at Capped Collections.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…