0
0
MongoDBquery~5 mins

Date and timestamp types in MongoDB

Choose your learning style9 modes available
Introduction

Dates and timestamps help you store and work with time information in your database. They let you track when things happen.

You want to save when a user signed up.
You need to record the time a message was sent.
You want to find records created within a certain date range.
You want to sort events by their date and time.
You want to calculate how old something is based on its date.
Syntax
MongoDB
ISODate("YYYY-MM-DDTHH:mm:ss.sssZ")
Timestamp(seconds, increment)

ISODate stores a date and time in a readable format.

Timestamp stores a special internal time used mainly for replication and ordering.

Examples
Insert an event with a date and time using ISODate.
MongoDB
db.events.insertOne({ event: "party", date: ISODate("2024-06-01T18:00:00Z") })
Insert a log with a timestamp using seconds and an increment.
MongoDB
db.logs.insertOne({ action: "login", time: Timestamp(1685600000, 1) })
Find records with a date on or after January 1, 2024.
MongoDB
db.records.find({ date: { $gte: ISODate("2024-01-01T00:00:00Z") } })
Sample Program

This example adds two users with signup dates. Then it finds users who signed up before June 1, 2024.

MongoDB
db.users.insertMany([
  { name: "Alice", signupDate: ISODate("2024-05-20T10:30:00Z") },
  { name: "Bob", signupDate: ISODate("2024-06-01T15:45:00Z") }
])

db.users.find({ signupDate: { $lt: ISODate("2024-06-01T00:00:00Z") } })
OutputSuccess
Important Notes

ISODate is the most common way to store dates in MongoDB.

Timestamps are mostly used internally and for special cases like replication.

Always store dates in UTC to avoid confusion with time zones.

Summary

Use ISODate to store readable date and time values.

Timestamp is a special type mainly for internal use.

Dates help you filter, sort, and calculate time-related data easily.