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

后端 未结 7 1563
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 12:11

Just like in MYSQL, I want an incrementing ID.

相关标签:
7条回答
  • 2020-12-05 13:03

    If you suspect your data could span more than a single server (aka shards) then go with Dennis and use the native ObjectId.

    If you prefer int/long id (looks better on urls) then you can start with naive implementation of a generator using the findAndModify as Chris suggested. When/if the performance/locking starts to be an issue you can upgrade your generator to implement Hi/Lo algorithm. This will result much less stress on the 'seq' collection. and practically eliminate this issue. (the client side generator is using a 'pool' and only contact the DB when it has no more free ids)

    0 讨论(0)
提交回复
热议问题