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

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

Just like in MYSQL, I want an incrementing ID.

7条回答
  •  感情败类
    2020-12-05 12:37

    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.

提交回复
热议问题