In MongoDb ObjectId is a 12-byte BSON type.
Is there any way to reduce the size of objectID?
In MongoDb ObjectId is a 12-byte BSON type.
Is there any way to reduce the size of objectID?
No. It's a BSON data type. It's like asking a 32-bit integer to shrink itself.
Every object must have _id property, but you are not restricted to ObjectId
.
Every document in a MongoDB collection needs to have a unique _id
but the value does not have to be an ObjectId
. Therefore, if you are looking to reduce the size of documents in your collection you have two choices:
Pick one of the unique properties of your documents and use it as the _id
field. For example, if you have an accounts collection where the account ID--provided externally--is part of your data model, you could store the account ID in the _id
field.
Manage primary keys for the collection yourself. Many drivers support custom primary key factories. As @assylias suggests, going with an int will give you good space savings but, still, you will use more space than if you can use one of the fields in your model as the _id
.
BTW, the value of an _id
field can be composite: you can use an Object/hash/map/dictionary. See, for example, this SO question.
If you are using some type of object/model framework on top of Mongo, I'd be careful with (1). Some frameworks have a hard time with developers overriding id generation. For example, I've had bad experience with Mongoid in Ruby. In that case, (2) may be the safer way to go as the generation happens at the driver layer.