A timestamp in MongoDB is a data type that records when a specific event or modification occurred in the database. This is useful for maintaining the order of transactions and performing operations like data synchronization, replication, recovery, and concurrency.
The Timestamp data type in MongoDB is a 64 bit value where:
- The first 32 bits are a time\_t value (seconds since the Unix epoch)
- The second 32 bits are an incrementing ordinal for operations within a given second.
While MongoDB has the Timestamp data type, it’s not typically used by developers. Instead, developers use the ‘Date’ data type which is simpler but still provides the necessary functionality for most use cases.
To add a field that defaults to the current date, you can use the $currentDate operator in an update operation:
```
db.collection.updateOne(
{ _id: 1 },
{ $currentDate: { lastModified: true } }
)
```
To insert current date and time in Date format, we can use the Date() function in insert operation:
```
db.collection.insert({createdAt: new Date()});
```
These will automatically be stored in the standard ISO 8601 format (like “2016-05-18T16:04:07.539Z”).
For the functionality of auto-updating a last updated timestamp, MongoDB doesn’t support this out of the box, but it can be handled in your application logic. A common usage is creating a ‘pre-save’ hook in Mongoose (MongoDB’s most common ORM) that will always update a ‘lastUpdated’ field before saving the document.
Keep in mind that while MongoDB stores times in UTC by default, it will convert to the local time zone when retrieving the data.