MongoDb:使用ObjectID与包含ID的字符串的好处是什么? [英] MongoDb: Benefit of using ObjectID vs a string containing an Id?

查看:717
本文介绍了MongoDb:使用ObjectID与包含ID的字符串的好处是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将ID作为对象ID存储到相关文档中相对于将其存储为字符串文字有什么好处吗?

Is there any benefit to storing an id to a related document as an ObjectId versus storing it as a string literal?

使用ObjectID:

Using ObjectID:

{
   "_id": ObjectId("522bb79455449d881b004d27"),
   "username": "admin",
   "folder": ObjectId("522bb79455449d881b004d23")
}

相对于字符串:

{
   "_id": ObjectId("522bb79455449d881b004d27"),
   "username": "admin",
   "folder": "522bb79455449d881b004d23"
}

对于我要将数据发送回客户端的API ...使用字符串意味着我不必清理"数据...而且我们必须进行第二次查询才能获取文件夹无论如何,文档...是否值得使用ObjectId? (如果可以,为什么?)

For my API where I'm sending data back to a client... using the string means I don't have to "cleanup" the data... and as we have to do a second query to get the folder document anyway... is it worth using ObjectId? (and if so why?)

谢谢

推荐答案

最大的原因是ObjectID为12个字节,而等效字符串为24个字节.在足够大的集合中,每个ID节省的那12个字节真的加起来!这些ID还意味着在读取或写入文档时通过导线传输的字节也更少.

The biggest reason is that ObjectIDs are 12 bytes, whereas an equivalent string is 24 bytes. Over a large enough collection, those 12 bytes saved per ID really add up! Those IDs also mean fewer bytes transferred over the wire when reading or writing the document, as well.

此外,某些ODM希望将ObjectID用于外部文档引用,并且可能会被ID的字符串版本所混淆.我对PHP ODM不够熟悉,无法说明这是否会特别影响您.

Additionally, some ODMs expect ObjectIDs for external document references, and may be confused by string versions of the ID. I am not familiar enough with PHP ODMs to say if this might affect you specifically, though.

不过,关于API方面,您可能应该在将数据发送到客户端之前先对数据进行规范化,因为由于Mongo不会强制执行架构,因此您可以在给定字段中使用任何类型的数据,因此,您可能有一些文档具有字符串ID,而另一些文档具有BSON ID,并且您的API会很乐意将它们都发送给客户端,但是一个或另一个可能会导致损坏.在这种情况下,应在文档中使用BSON ObjectID,然后将其转换为API输出中的字符串.

Regarding the API stuff, though, you should probably be doing normalization of the data before sending it to the client anyhow, because since Mongo doesn't enforce a schema, you can have literally any sort of data in a given field, so you might have some documents that have string IDs, and others that have BSON IDs, and your API would happily send them both through to the client, but one or the other might cause breakage. In this particular case, you should use BSON ObjectIDs in your documents, and then should cast them to strings in your API output.

这篇关于MongoDb:使用ObjectID与包含ID的字符串的好处是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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