MongoDB storing arrays of ObjectId's

让人想犯罪 __ 提交于 2019-12-09 05:08:45

问题


In my database I have to store an array of object ids. What should I use? Something like this:

[ObjectId("50350e12a36feb1be6000364"), ObjectId("57350e12a37fef1be6000922"), ObjectId("10350e17d34ffb1be6200925")]

or something like this:

["50350e12a36feb1be6000364", "57350e12a37fef1be6000922", "10350e17d34ffb1be6200925"]

I could save space with the second, and then cast to ObjectId, but am I loosing anything by using this approach? Do ObjectIds behave like foreign keys in relational databases?


回答1:


I would definitely go with the first approach, storing the ObjectIds directly. This saves space, as ObjectId is 12 bytes whereas the second approach string is 24 bytes.

Also, if the ObjectIds are used to fetch the objects later, storing as ObjectId saves some hassle.




回答2:


Unless you have a good reason not to, store them as an array of ObjectIds. It's more compact (12 bytes vs. 24) and it more accurately reflects what's stored. It can also enable driver-level support for following ObjectId references.



来源:https://stackoverflow.com/questions/12464823/mongodb-storing-arrays-of-objectids

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!