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

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

mysql - How do you implement an auto-incrementing primary ID in MongoDB?

Just like in MYSQL, I want an incrementing ID.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...