mongodb的id的唯一性_关于Mongoid:在MongoDB中创建简短的唯一对象ID

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

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

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

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

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

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

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

非常有用的答案,但是为什么用22个拉丁字母+ 10位数字而不是26个拉丁字母+ 10位数字?

好点子! 不知道为什么我写了22 :)

我们可以更深入地使用52个拉丁字母,10位数字和一些其他文字_- =),然后使用radix64,我们得到长度为log64(2^96) = 16而不是原始的log16(2^96) = 24。

您可以尝试Mongoid :: Token

https://github.com/thetron/mongoid_token

从文档:

This library is a quick and simple way to generate unique, random

tokens for your mongoid documents, in the cases where you can't, or

don't want to use slugs, or the default MongoDB IDs.

Mongoid::Token can help turn this:

http://myawesomewebapp.com/video/4dcfbb3c6a4f1d4c4a000012/edit

Into something more like this:

http://myawesomewebapp.com/video/83xQ3r/edit

为什么不使用dylang / shortid?

使用npm npmjs.com/package/shortid安装:

npm i shortid

然后要求:

const shortid = require('shortid');

在猫鼬模式中:

new Schema {

_id: {

type: String,

default: shortid.generate

}

}

或直接插入:

users.insert({

_id: shortid.generate()

name: ...

email: ...

});

尝试gem https://github.com/jffjs/mongoid_auto_inc

@aav提到您可以使用前4个字节,但是此值以秒为单位,您甚至可以每秒获得10.000或更多的插入。其他的对象objectID是Uniq,您需要检查"何时",如果您从重复值" Write Concerns"中得到错误?

new Date().getTime() - is in milliseconds => 1557702577900 why not use last 4 bytes ?

这段代码看起来很有趣:

https://github.com/treygriffith/short-mongo-id/blob/master/lib/objectIdToShortId.js

还要检查ObjectID时间戳解析器:

https://steveridout.github.io/mongo-object-time/

或者,您可以执行ObjectId()。toString(),并通过哈希值[nodejs,php和许多其他]创建此字符串的基数

Maybe best options it to use 4-5 bytes from js timestamp and INC from

bson then hash this value by hids

Database 3milion rows numeric increment"_id" size on disk => 76MB, default object id => 86MB

Hashids库用于生成这样的ID。在这里查看? https://github.com/peterhellberg/hashids.rb

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值