Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Just like in MYSQL, I want an incrementing ID.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
492 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...