3

In MongoDb ObjectId is a 12-byte BSON type.

Is there any way to reduce the size of objectID?

Oksana
  • 13,442
  • 10
  • 53
  • 89
  • Maybe I don't understand your question, but reduce it how? It's designed to be a simple and efficient way to get a unique identifier defined within a multi-machine setup: a 4-byte value representing the seconds since the Unix epoch, a 3-byte machine identifier, a 2-byte process id, and a 3-byte counter, starting with a random value. – WiredPrairie Apr 07 '13 at 18:22
  • 1
    That is not possible but you can use an integer as the `_id` instead of an ObjectId to only use 4 bytes. – assylias Apr 07 '13 at 19:07
  • What language, driver & mapping framework (if any) are you using? – Sim Apr 08 '13 at 02:23
  • Maybe this can help: https://github.com/Rightech/shrink-mongo-id – standac Apr 28 '20 at 14:22

2 Answers2

2

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.

Ori Dar
  • 18,687
  • 5
  • 58
  • 72
  • 1
    Addition: Every top-level *document* in a MongoDB collection must have an _id, which acts as the primary key. When this property is not set in code, it is automatically assigned by a driver or by the database. – WiredPrairie Apr 07 '13 at 18:25
2

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:

  1. 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.

  2. 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.

Community
  • 1
  • 1
Sim
  • 13,147
  • 9
  • 66
  • 95