Creating incrementing numbers with mongoDB

后端 未结 2 903
暖寄归人
暖寄归人 2021-01-29 03:44

We have an order system where every order has an id. For accounting purposes we need a way to generate invoices with incremening numbers. What is the best way to do this without

2条回答
  •  北海茫月
    2021-01-29 04:16

    http://www.mongodb.org/display/DOCS/How+to+Make+an+Auto+Incrementing+Field

    The first approach is keeping counters in a side document:

    One can keep a counter of the current _id in a side document, in a collection dedicated to counters. Then use FindAndModify to atomically obtain an id and increment the counter.

    The other approach is to loop optimistically and handle dup key error code of 11000 by continuing and incrementing the id for the edge case of collisions. That works well unless there's high concurrency writes to a specific collection.

    One can do it with an optimistic concurrency "insert if not present" loop.

    But be aware of the warning on that page:

    Generally in MongoDB, one does not use an auto-increment pattern for _id's (or other fields), as this does not scale up well on large database clusters. Instead one typically uses Object IDs.

    Other things to consider:

    • Timestamp - unique long but not incrementing (base on epoch)
    • Hybrid Approach - apps don't necessarily have to pick one storage option.
    • Come up with your id mechanism based on things like customer, date/time parts etc... that you generate and handle collisions for. Depending on the scheme, collisions can be much less likely. Not necessarily incrementing but is unique and has a well defined readable pattern.

提交回复
热议问题