true_north_404
true_north_404

Reputation: 177

Why does MongoDB create _ids as objects?

The _ids that are generated by MongoDB are always in this form: ObjectId("5f1b0e51b931af765f21edd4")

If the main reason for creating the _id column is to have something to uniquely identifies a document why is the generated _id format not simply in this form "5f1b0e51b931af765f21edd4.

I don't know if I'm right, but also I suspect that the first format occupies more space.

Upvotes: 0

Views: 478

Answers (2)

kmdreko
kmdreko

Reputation: 60682

ObjectId is a special type in Mongo. It is not like a normal object/document and only takes up 12-bytes. The ObjectId("24-character-hex-string") is just its human-readable notation.

A 24-character string takes up at least 24-bytes, and if we look up the bson spec, stores an additional 4-bytes for length and 1-byte for a null terminator, so 29-bytes total.

Upvotes: 1

D. SM
D. SM

Reputation: 14530

The _ids that are generated by MongoDB are always in this form: ObjectId("5f1b0e51b931af765f21edd4")

Not at all. Ids generated by MongoDB are 12-byte byte sequences. mongo shell uses the rendering ObjectId("xxx") to indicate that the value is stored as a 12-byte ObjectId and not as a 24-byte string, which is what "5f1b0e51b931af765f21edd4" is.

I don't know if I'm right, but also I suspect that the first format occupies more space.

As stored by the server, ObjectId occupies less space than a hex string you see on your screen (half as much, in fact). To convey this compact storage, the rendering of an ObjectId occupies more space on your screen.

Upvotes: 1

Related Questions