BSON_OID(3)

πŸ“¦
version 1.26.0 Β· 3 versions
, in ubuntu noble

πŸ’– BSON_OID πŸ’– β€” the libbson manual, section 3, bestie

okay so this is the ObjectID page of the libbson manual and honestly she's iconic. Libbson gives you a simple way to generate ObjectIDs, and you can do it in a single-threaded or multi-threaded manner, depending on your requirements. no cap. πŸ’…

The bson_oid_t structure represents an ObjectID in MongoDB. It is a 96-bit identifier. that's the whole vibe. ✨


🧬 COMPOSITION 🧬

here's what's inside a bson_oid_t, byte by byte, and yes we are counting:

  • 4 bytes β€” the UNIX timestamp, in big-endian format. ⏰
  • 5 bytes β€” a random number. 🎲
  • 3 bytes β€” a 24-bit monotonic counter incrementing from rand(), in big-endian. πŸ“ˆ

πŸ”€ SORTING OBJECTIDS πŸ”€

The typical way to sort in C is using qsort(). So Libbson said "say less" and provides a qsort() compatible callback function named bson_oid_compare(). It returns less than 1, greater than 1, or 0, depending on the equality of two bson_oid_t structures. 🌈


πŸͺž COMPARING OBJECT IDS πŸͺž

If you simply want to compare two bson_oid_t structures for equality, use bson_oid_equal(). easy peasy, that's the whole thing. 🫢


πŸŽ€ GENERATING πŸŽ€

To generate a bson_oid_t, you may use the following:

bson_oid_t oid;

bson_oid_init (&oid, NULL);

boom, born, slay. 🍼✨


πŸ” PARSING OBJECTID STRINGS πŸ”

You can also parse a string containing a bson_oid_t.

⚠️ The input string MUST be 24 characters or more in length. like, non-negotiable, bestie.
bson_oid_t oid;

bson_oid_init_from_string (&oid, "123456789012345678901234");
bson_oid_t oid;

bson_oid_init_from_string_unsafe (&oid, "123456789012345678901234");

#️⃣ HASHING OBJECTIDS #️⃣

If you need to store items in a hashtable, you may want to use the bson_oid_t as the key. Libbson provides a hash function for just this purpose. It is based on DJB hash. πŸ’œ

unsigned hash;

hash = bson_oid_hash (oid);

⏳ FETCHING OBJECTID CREATION TIME ⏳

You can easily fetch the time that a bson_oid_t was generated using bson_oid_get_time_t(). πŸ•°οΈ

time_t t;

t = bson_oid_get_time_t (oid);
printf ("The OID was generated at %u\n", (unsigned) t);

πŸ‘‘ AUTHOR πŸ‘‘

MongoDB, Inc πŸ’…

2017-present, MongoDB, Inc


and that's the page, bestie πŸŽ€ this whole thing is libbson 1.26.0, dated Mar 31, 2024, and it lives at BSON_OID(3). go forth and generate your little 96-bit icons. πŸ’–βœ¨πŸ¦‹

πŸ“¦ where this page comes from