# Tech Dive 1: MongoDB's ObjectId

MongoDB is a famous NoSQL Database. If you're just getting started with MongoDB, I would suggest you begin with [Mongo University](https://learn.mongodb.com/)

## Anatomy

MongoDB's ObjectID is made of 12 bytes. The 12 bytes consists of

* a 4-byte timestamp.
    
* a 5-byte random value generated once per process.
    
* a 3-byte incrementing counter initialized to a random value.
    

Example:

```markdown
65f87920068c7d17cb1288d6
```

`65f87920` - [Unix Epoch](https://en.wikipedia.org/wiki/Unix_time) Timestamp

`068c7d17cb` - Random Value

`1288d6` - Incrementing Counter

## Constructing ObjectId

You can use the `ObjectId()` method to construct a new ObjectId.

Optionally, it can take two inputs.

1. `hexadecimal` - A 24-character hexadecimal string value.
    
2. `integer` - The integer value, in seconds, is added to the Unix epoch to create the new timestamp.
    
    Example:
    
    ```bash
    > ObjectId(10)
    < ObjectId('0000000a0d098c2eda0f296e')
    ```
    

## Methods you can use on ObjectId

### getTimestamp()

![Movie gif. Rowan Atkinson as Mr. Bean in Mr. Bean's Holiday, stands in a field of yellow flowers on a windy day. He looks off into the distance and then at his watch, before scratching his head. ](https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExemFmMzU5aHpxbTZxbTFmYm94N2R5cXRsYWlscTlrdjc2aGJpbTd3diZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/QBd2kLB5qDmysEXre9/giphy.gif align="center")

Since the timestamp is included in the ObjectId, you can retrieve the time in which the ObjectId was generated.

```bash
> ObjectId('665377378755af3d1e7c5701').getTimestamp()
< 2024-05-26T17:53:59.000Z

> ObjectId('0000000a0d098c2eda0f296e').getTimestamp()
< 1970-01-01T00:00:10.000Z
```

### toString()

You can use this method in case if you want to convert the ObjectId to hexadecimal string.

```bash
> ObjectId('665b4d520d098c2eda0f296d').toString()
< 665b4d520d098c2eda0f296d
```

---

If you’re a tech enthusiast and resonate with my content, follow me on [LinkedIn](https://www.linkedin.com/in/bmonish/), [GitHub](https://github.com/bmonish), and [Twitter](https://twitter.com/iammonishb).
