Creating short, unique object id's in MongoDB

2020-02-08 17:44发布

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?

6条回答
祖国的老花朵
2楼-- · 2020-02-08 18:26

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: ...
        });
查看更多
萌系小妹纸
4楼-- · 2020-02-08 18:29

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/

查看更多
我命由我不由天
5楼-- · 2020-02-08 18:29

@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 ?

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

Database 3milion rows numeric increment "_id" size on disk => 76MB, default object id => 86MB
查看更多
唯我独甜
6楼-- · 2020-02-08 18:46

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

查看更多
女痞
7楼-- · 2020-02-08 18:50

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

查看更多
登录 后发表回答