在 MongoDB 中创建简短、唯一的对象 ID

发布于 2024-11-06 00:15:16 字数 231 浏览 0 评论 0 原文

我正在使用 Rails/Mongoid 制作一个类似于 Instagram 的应用程序。我想要一个可以在 http://instagr.am/p/DJmU8/< 等网址中使用的唯一 ID /a>

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

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/

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

圈圈圆圆圈圈 2024-11-13 00:15:16

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

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

有关 mongo 的 ObjectID 结构的更多详细信息,请参见:http://www.mongodb.org/ display/DOCS/Object+IDs

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

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

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

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.

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

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.

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

骑趴 2024-11-13 00:15:16

为什么不使用 dylang/shortid

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

npm i shortid

然后 require:

const shortid = require('shortid');

在 mongoose schema 中:

    new Schema {
        _id: {
            type: String,
            default: shortid.generate
        }
    }

或者只是直接插入:

    users.insert({
        _id: shortid.generate()
        name: ...
        email: ...
        });

Why not use dylang/shortid?

Install using npm npmjs.com/package/shortid:

npm i shortid

Then require:

const shortid = require('shortid');

In mongoose schema:

    new Schema {
        _id: {
            type: String,
            default: shortid.generate
        }
    }

or just insert directly:

    users.insert({
        _id: shortid.generate()
        name: ...
        email: ...
        });
溇涏 2024-11-13 00:15:16

您可以尝试 Mongoid::Token

https://github.com/thetron/mongoid_token

从文档中:

这个库是一种快速、简单的方法来生成独特的、随机的
如果您不能,则为您的 mongoid 文档提供令牌,或者
不想使用 slugs 或默认的 MongoDB ID。

Mongoid::Token 可以帮助扭转这个局面:

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

更像这样:

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

You could try Mongoid::Token

https://github.com/thetron/mongoid_token

From the docs:

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

誰認得朕 2024-11-13 00:15:16

@aav 提到您可以使用前 4 个字节,但该值以秒为单位,您甚至可以每秒插入 10.000 或更多。另外,objectID 是 Uniq,您需要检查“何时”从重复值“Write Concerns”中收到错误?

new Date().getTime() - 以毫秒为单位=> 1557702577900 为什么不使用最后 4 个字节? Base62 中的时间戳为 rqiJgPq

此代码看起来很有趣:

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

另请检查 ObjectID 时间戳解析器:

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

或者您可以执行 ObjectId().toString() 并通过 hashids [nodejs、php 等等]

也许最好的选择是使用 js 时间戳和 INC 中的 4-5 个字节
bson 然后通过 hids 对该值进行哈希

bson 然后通过 hids 在此处输入图像描述

var id = ObjectID('61e33b8467a45920f80eba52').toString();

console.log("id:", id);
console.log("timestamp:", parseInt(id.substring(0, 8),16).toString());
console.log("machineID:", parseInt(id.substring(8, 14),16) );
console.log("processID:", parseInt(id.substring(14, 18),16) );
console.log("counter:", parseInt(id.slice(-6),16) );

var ObjTimestamp = parseInt(ObjectID2.substring(0, 8),16).toString().slice(-5);
var Counter = parseInt(ObjectID2.slice(-6),16);
//https://github.com/base62/base62.js/
console.log('Final:',base62.encode(parseInt(Counter) + parseInt(ObjTimestamp)  )); 

输出:

vI7o
15V9L
5t4l

如果有以下情况,您可能会发生冲突:更多进程正在运行,然后考虑将 PID 添加到唯一的并且当您在不同计算机上运行多个实例时

@aav was mention that you can use first 4 bytes, but this value are in seconds and you can get even 10.000 or more insert per seconds. Other thing objectID is Uniq and you need check "when" you get error from duplicate value "Write Concerns"?

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

This code look interesting:

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

Check also ObjectID timestamp parser:

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

Or you can execute ObjectId().toString() and base of this string create new by hashids [nodejs,php, andmanymore]

Maybe best options it to use 4-5 bytes from js timestamp and INC from
bson then hash this value by hids

enter image description here

var id = ObjectID('61e33b8467a45920f80eba52').toString();

console.log("id:", id);
console.log("timestamp:", parseInt(id.substring(0, 8),16).toString());
console.log("machineID:", parseInt(id.substring(8, 14),16) );
console.log("processID:", parseInt(id.substring(14, 18),16) );
console.log("counter:", parseInt(id.slice(-6),16) );

var ObjTimestamp = parseInt(ObjectID2.substring(0, 8),16).toString().slice(-5);
var Counter = parseInt(ObjectID2.slice(-6),16);
//https://github.com/base62/base62.js/
console.log('Final:',base62.encode(parseInt(Counter) + parseInt(ObjTimestamp)  )); 

Output:

vI7o
15V9L
5t4l

You can get collision if: more process are running, then consider add PID to unique and when you run multiple instance on different computer

灼痛 2024-11-13 00:15:16

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

The Hashids library is meant for generating IDs like this. Check it out here ☞ https://github.com/peterhellberg/hashids.rb

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文