Mongodb ObjectID 在文档之间是唯一的吗? [英] Is Mongodb ObjectID unique between documents?

查看:88
本文介绍了Mongodb ObjectID 在文档之间是唯一的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑一个博客站点的例子,我想在两个不同的文档中保存问题和回复.我知道这也可以通过 Embedding 文档来完成,但假设我们想要两个不同的文档.

Lets consider an example of blog site where I want to save questions and replies in two different documents. I know this can also be done with Embedding documents but lets assume we want two different documents.

而且我在问题和回复上都有 Like 选项.如果用户喜欢某个问题,则特定的 question 的 objectID 存储在 Like 文档中,对于喜欢的回复也是如此.

And I have Like option on both question and reply. If user likes a question that particular question's objectID is stored inside a Like document and similarly for likes in reply.

现在我想知道我存储在 Like 文档中的 objectID's 是否会产生冲突.就像 question 的 objectid 与任何 reply 的 objectidsame 一样.有没有可能有这样的冲突??

Now I wonder whether the objectID's that I store in Like documents could create a conflict. Like if the question's objectid is same as any reply's objectid. IS it possible to have such conflicts??

在 Mongodb ObjectID 文档中提供了以下内容:

In Mongodb ObjectID documentation the following is provided:

ObjectId 是一个 12 字节的 BSON 类型,使用:

ObjectId is a 12-byte BSON type, constructed using:

一个 4 字节的值,表示自 Unix 纪元以来的秒数,

a 4-byte value representing the seconds since the Unix epoch,

一个 3 字节的机器标识符,

a 3-bytemachine identifier,

一个 2 字节的进程 ID,和

a 2-byte process id, and

一个 3 字节的计数器,从一个随机值开始.

a 3-byte counter, starting with a random value.

推荐答案

它对于所有实际用途都是独一无二的.提到的非唯一性是一个相当理论性的.

It is unique for all practical purposes. The non- uniqueness mentioned is a rather theoretical one.

ObjectId 由

The ObjectId is constructed out of

  • 时间戳(自纪元以来的秒数)
  • 机器标识符
  • 进程标识
  • 和一个 3 字节的计数器,以 每秒一个随机值开始

因此,在中位数中,除非您为每个客户端每秒写入超过 3080 个文档,否则您应该节省.需要注意的是,_id 有一个唯一的约束:即使 如果您尝试写入相同的 ObjectId 两次,也会有一个例外.

So, at median, unless you write in excess of 3080 documents per second per client, you should be save. It is to note that _id has an unique constraint: Even if you'd try to write the same ObjectId twice, there'd be an exception.

旁注:即使是像 MD5 或(在较小程度上)SHA256 这样的哈希算法也有轻微的冲突机会.但是有一个独特的约束,你是安全的.

Side note: even hash algorithms like MD5 or (to a lesser extent) SHA256 have a slight chance of collision. But with a unique constraint, you are safe.

编辑:由于在非常、非常、非常罕见的情况下会抛出异常,即生成并尝试同时写入两个相同的 ObjectId,您只需通过生成新的 ObjectId 来处理它们,然后尝试再次保存文档.

Edit: Since an exception is thrown in the very, Very, VERY rare case that two identical ObjectIds are generated and tried to be written concurrently, you simply handle them by generating a new ObjectId and try to save the document again.

这篇关于Mongodb ObjectID 在文档之间是唯一的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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