在JavaScript中缩短MongoDB ID [英] Shorten MongoDB ID in javascript

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

问题描述

如何将mongodb ID缩短为更容易解析的语法,以用于URL.该字符串在当前迭代中太长了.

Base64不错,但仍然太长.我正在寻找7位以下字符范围内的更多内容.

我希望能够在node.js和浏览器中对其进行编码/解码.

解决方案

从请求中解析ObjectId并不困难(因此我不确定为什么会出现问题?).如果目标是创建可键入的URL,那么使用更短且更友好"的URL将很有价值.

在分片的MongoDB设置中,不能采用保证唯一的12个字节的数字并将其压缩为少于12个字节,并保证它是唯一的(例如,您提到的7个字符以下).

docs 中,MongoDB ObjectId包含:

  • 4字节时间戳记
  • 3字节机器标识符
  • 2字节的进程ID
  • 和一个3字节计数器.

因此,您要么需要牺牲ObjectId的一部分(并因此进行分片),要么设计索引的替代ID创建格式.

虽然您可能会散列ID,但同样会产生您想要为其编码的冲突(再次,您不能将12个字节缩减为4个字节并保证唯一性).并且,如果有可能发生冲突(并且减少可用位数的总和),那么无论如何您都将需要某种二级表(并且您需要创建一个索引来将生成的ID转换为ObjectId)

结果选项:

  • 删除通常重要的位-如果执行此操作,不要分片集合
  • 设计您自己的独特ID解决方案(并且如果在网络农场中,它最终看起来可能与MongoDB非常相似以处理唯一性)
  • 将ObjectId用作长整数并对其运行缩短的算法(由于它超出了JavaScript的53位数字精度,因此需要首先分解为较小的块),请尝试使用此算法,例如= 解决方案

Parsing the ObjectId from a request wouldn't be difficult (so I'm not sure why that is a problem?). If the goal is to make typeable URLs, then having a shorter and "friendlier" URL would be valuable.

You can't take a 12 byte number that is guaranteed unique in a sharded MongoDB setup and condense it to fewer than 12 bytes and have it be guaranteed unique (you mentioned under seven characters for example).

From the docs, the MongoDB ObjectId consists of:

  • a 4-byte timestamp
  • a 3-byte machine identifier
  • a 2-byte process id
  • and a 3-byte counter.

So, you'll either need to sacrifice some portion of the ObjectId (and hence sharding), or devise an alternate Id creation format that is indexed.

While you could hash the ID potentially, again, conflicts can arise that you'd want to code for (again, you can't take 12 bytes down to 4 bytes and guarantee uniqueness). And if there are conflicts possible (and there will be if you reduce the total number of bits available), you'll need some sort of secondary table anyway (and you'd need to create an index to go from generated ID to ObjectId).

Resulting options:

  • Remove normally significant bits -- if you do this, don't shard the collection
  • Devise your own your own unique ID solution (and if it's in a web-farm, it may end up looking very similar to MongoDB's to handle uniqueness)
  • use the ObjectId as a long number and run a shorten algorithm on it (it will need to be broken down first into smaller chunks as it exceeds JavaScript's numeric precision of 53 bits), try this algorithm for example = encode it (will end up around 17 characters)
  • use something else shorter, but unique as the Id for your documents
  • Easiest: Just accept that the Ids are long. :)

(It's not clear why the browser would need to do this conversion--why would it have the document's ObjectID?)

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

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