0
0
MongodbConceptBeginner · 3 min read

What is Date Type in MongoDB: Explanation and Examples

In MongoDB, the Date type stores date and time information as a 64-bit integer representing milliseconds since the Unix epoch (January 1, 1970). It allows you to save and query dates and times easily in your documents.
⚙️

How It Works

The Date type in MongoDB works like a timestamp that counts milliseconds from a fixed point in time called the Unix epoch (January 1, 1970). Think of it as a stopwatch that started ticking at that moment and keeps counting milliseconds forward.

This lets MongoDB store exact moments in time, including both the date and the time of day. When you save a Date value, MongoDB keeps it in a special format that makes it easy to compare, sort, and query by dates.

For example, you can find all documents created before or after a certain date, or calculate how many days have passed between two dates. This is very useful for things like tracking events, logs, or user activity.

💻

Example

This example shows how to insert a document with a Date field and then query documents by date.

mongodb
db.events.insertOne({ name: "Meeting", date: new Date("2024-06-01T10:00:00Z") })
db.events.find({ date: { $gte: new Date("2024-06-01T00:00:00Z") } })
Output
{ "_id" : ObjectId("...") , "name" : "Meeting", "date" : ISODate("2024-06-01T10:00:00Z") }
🎯

When to Use

Use the Date type whenever you need to store information about specific points in time. This includes:

  • Recording when a user signed up or logged in
  • Tracking event start and end times
  • Logging actions with timestamps
  • Scheduling tasks or reminders

Using the Date type helps you perform queries like finding recent records, filtering by date ranges, or sorting by time, which are common needs in many applications.

Key Points

  • The Date type stores time as milliseconds since January 1, 1970 (Unix epoch).
  • It includes both date and time information.
  • MongoDB provides easy ways to create and query Date values.
  • Use it for any data that involves timestamps or scheduling.

Key Takeaways

MongoDB's Date type stores date and time as milliseconds since the Unix epoch.
Use Date type to save exact moments for events, logs, or scheduling.
You can query and sort documents easily by Date fields.
Date values include both date and time information.
Creating Date values uses JavaScript's Date object syntax.