---
name: "bson_oid"
section: "3"
platform: "linux"
package: "libbson-doc"
version: "1.23.1-1+deb12u3"
release: "Debian 12 (Bookworm)"
platforms: ["linux"]
url: "https://new.carta.tech/bson_oid"
---

# bson\_oid(3)

ObjectIDs Libbson provides a simple way to generate ObjectIDs. It can be used in a single-threaded or multi-threaded manner depending on your requirements. The bson\_oid\_t structure represents an ObjectID in MongoDB. It is a 96-bit identifier.

## NAME

bson\_oid - ObjectIDs

Libbson provides a simple way to generate ObjectIDs. It can be used in a single-threaded or multi-threaded manner depending on your requirements.

The *bson\_oid\_t* structure represents an **ObjectID** in MongoDB. It is a 96-bit identifier.

## COMPOSITION

- •

  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()**. Therefore, Libbson 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()*.

## GENERATING

To generate a *bson\_oid\_t*, you may use the following.

```
bson_oid_t oid;
bson_oid_init (&oid, NULL);
```

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

```
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

## COPYRIGHT

2017-present, MongoDB, Inc
