使用mongoDB创建递增数字 [英] Creating incrementing numbers with mongoDB

查看:238
本文介绍了使用mongoDB创建递增数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个订单系统,其中每个订单都有一个ID.出于会计目的,我们需要一种生成编号递增的发票的方法.在不使用sql数据库的情况下执行此操作的最佳方法是什么? 我们正在使用节点来实现该应用程序.

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 using an sql database? We are using node to implement the application.

推荐答案

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

第一种方法是在辅助文档中保留计数器:

The first approach is keeping counters in a side document:

您可以在辅助文档中保留当前_id的计数器, 专用于柜台的收藏品.然后使用FindAndModify原子地 获取ID并增加计数器.

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.

另一种方法是乐观地循环并通过为冲突的边缘情况继续并增加id来处理11000的dup键错误代码.除非对特定集合进行高并发写入,否则这将很好地工作.

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:

通常在MongoDB中,不使用自动递增模式 _id(或其他字段),因为这在大型数据库集群上无法很好地扩展.相反,通常使用对象ID.

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.

要考虑的其他事项:

  • 时间戳-唯一长但不递增(基于历元)
  • 混合方法-应用程序不一定必须选择一个存储选项.
  • 根据您生成并处理碰撞的客户,日期/时间部分等...来使用id机制.根据方案的不同,发生碰撞的可能性要小得多.不一定要递增,而是唯一的,并具有定义明确的可读模式.
  • 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.

这篇关于使用mongoDB创建递增数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆