在MongoDB中创建简短的唯一对象ID [英] Creating short, unique object id's in MongoDB

查看:93
本文介绍了在MongoDB中创建简短的唯一对象ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Rails/Mongoid制作类似于instagram的应用.我想要一个可以在URL中使用的唯一ID,例如 http://instagr.am/p/DJmU8/

I'm making an app similar to instagram using Rails/Mongoid. I want a unique ID that I can use in a url like http://instagr.am/p/DJmU8/

最简单的方法是什么?我可以从Mongo创建的默认BSON ObjectID派生出这样的ID吗?

What's the easiest way to do that? Can I derive such an ID from the default BSON ObjectID Mongo creates?

推荐答案

您可以尝试使用ObjectID的前4个字节(它们将代表时间戳).

You may try to use first 4 bytes of ObjectID (they will represent timestamp).

但是,为了100%安全,最好通过实现计数器来产生真正唯一的短id.您可以使用单独的集合来维护计数器的当前值.

But, to be 100% safe, it's better to produce really unique short id, by implementing a counter. You can use separate collection to maintain current value of your counter.

有关mongo的ObjectID结构的更多详细信息,可以在这里找到: http://www.mongodb .org/display/DOCS/Object + IDs

More details on mongo's ObjectID structure can be found here: http://www.mongodb.org/display/DOCS/Object+IDs

作为替代方案,您可以将转换十六进制字符串id表示形式转换为基于36个符号(26个拉丁字母+ 10位数字)的表示形式.显然会更短.

As an alternative you can convert convert hex string id representation to a representation based on 36 symbols (26 latin letters + 10 digits). It will obviously be shorter.

似乎有一个ruby库,可以进行此类转换 http://rubyworks.github. com/radix/

It seems, that there is a ruby library, that can do such conversions http://rubyworks.github.com/radix/

这篇关于在MongoDB中创建简短的唯一对象ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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