我应该在MongoDB中实现自动增量吗? [英] Should I implement auto-incrementing in MongoDB?

查看:83
本文介绍了我应该在MongoDB中实现自动增量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从MySQL切换到MongoDB.对我来说,对于非常基本的users表而言,熟悉的体系结构会自动递增uid. 有关此用例,请参阅Mongo自己的文档.

I'm making the switch to MongoDB from MySQL. A familiar architecture to me for a very basic users table would have auto-incrementing of the uid. See Mongo's own documentation for this use case.

我想知道这是否是最佳的架构决策.从UX的角度来看,我喜欢将UID用作外部引用,例如在较短的URL中:http://example.com/users/12345

I'm wondering whether this is the best architectural decision. From a UX standpoint, I like having UIDs as external references, for example in shorter URLs: http://example.com/users/12345

还有第三种方法吗? IRC Freenode #mongodb中的某人建议创建一系列ID并将其缓存.我不确定如何真正实现它,或者我是否可以走另一条路.我什至不需要_id本身以这种方式递增.只要users在文档中都具有唯一的数字uid,我就会很高兴.

Is there a third way? Someone in IRC Freenode's #mongodb suggested creating a range of IDs and caching them. I'm unsure of how to actually implement that, or whether there's another route I can go. I don't necessarily even need the _id itself to be incremented this way. As long as the users all have a unique numerical uid within the document, I would be happy.

推荐答案

乔什, MongoDB中没有自动增量ID,并且有充分的理由. 我要说的是在集群中唯一的ObjectId.

Josh, No auto-increment id in MongoDB and there are good reasons. I would say go with ObjectIds which are unique in the cluster.

您可以通过序列集合添加自动增量,并使用findAndModify获得下一个要使用的ID.这肯定会增加应用程序的复杂性,也可能影响分片数据库的能力.

You can add auto increment by a sequence collection and using findAndModify to get the next id to use. This will definitely add complexities to your application and may also affect the ability to shard your database.

只要您可以保证生成的ID是唯一的,就可以了. 但是头痛将在那里.

As long as you can guarantee that your generated ids will be unique, you will be fine. But the headache will be there.

您可以在MongoDB专用的google组中查看有关此问题的更多信息:

You can look at this post for more info about this question in the dedicated google group for MongoDB:

http://groups.google .com/group/mongodb-user/browse_thread/thread/f57b712b2aae6f0b/b4315285e689b9a7?lnk = gst& q = projapati#b4315285e689b9a7

希望这会有所帮助.

谢谢

这篇关于我应该在MongoDB中实现自动增量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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