Difference between storing an ObjectId and its string form, in MongoDB

后端 未结 2 1209
南笙
南笙 2020-12-24 11:02

I\'m a little confused by Mongo DB\'s use of ObjectIds. Sure they\'re great for creating IDs client-side that almost definitely don\'t conflict with other client-side create

2条回答
  •  死守一世寂寞
    2020-12-24 11:38

    I, personally, blame your code. I get around this pefectly fine in my applications by coding the right way. I convert to string in code to compare and I ensure that anything that looks like an ObjectId is actually used as a ObjectId.

    It is good to note that between the ObjectId (http://docs.mongodb.org/manual/reference/object-id/) and it's hex representation there is in fact 12 bytes of difference, the ObjectId being 12 bytes and it's hex representation being 24.

    Not only is it about storage efficiency but also about indexes; not just because they are smaller but also since the ObjectId can be used in a special manner to ensure that only parts of the index are loaded; the parts that are used. This becomes most noticeable when inserting, where only the latest part of that index needs to be loaded in to ensure uniqueness. You cannot guarantee such behaviour with its hex representation.

    I would strongly recommend you do not use the OjbectId's hex representation. If you want to "make your life easier" you would be better off creating a different _id which is smaller but somehow just as unique and index friendly.

提交回复
热议问题