mgo - bson.ObjectId vs string id

扶醉桌前 提交于 2019-12-07 06:57:25

As was already mentioned in the comments, storing the ObjectId as a hex string would double the space needed for it and in case you want to extract one of its values, you'd first need to construct an ObjectId from that string.

But you have a misconception. There is absolutely no need to use an ObjectId for the mandatory _id field. Quite often, I advice against that. Here is why.

Take the simple example of a book, relations and some other considerations set aside for simplicty:

{
  _id: ObjectId("56b0d36c23da2af0363abe37"),
  isbn: "978-3453056657",
  title: "Neuromancer",
  author: "William Gibson",
  language: "German"
}

Now, what use would have the ObjectId here? Actually none. It would be an index with hardly any use, since you would never search your book databases by an artificial key like that. It holds no semantic value. It would be a unique ID for an object which already has a globally unique ID – the ISBN.

So we simplify our book document like this:

{
  _id: "978-3453056657",
  title: "Neuromancer",
  author: "William Gibson",
  language: "German"
}

We have reduced the size of the document, make use of a preexisting globally unique ID and do not have a basically unused index.

Back to your basic question wether you loose something by not using ObjectIds: Quite often, not using the ObjectId is the better choice. But if you use it, use the binary form.

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