Visit complete MongoDB roadmap

← Back to Topics List

Date

In MongoDB, the Date datatype is used to store the date and time values in a specific format. This is essential when working with date-based data, such as recording timestamps, scheduling events, or organizing data based on time.

Date Format

MongoDB internally stores dates as the number of milliseconds since the Unix epoch (January 1, 1970). This BSON data format makes it efficient for storing and querying date values. However, when working with dates in your application, it is common to use a human-readable format such as ISO 8601.

Working with Date

To create a new Date instance, you can use the JavaScript Date object. Here’s an example:

const currentDate = new Date();

When inserting a document with a Date field, you can store the date value as follows:

db.events.insertOne({ title: 'Sample Event', eventDate: new Date() });

You can also specifically store the current date and time using MongoDB’s $currentDate operator:

db.events.insertOne({
  title: 'Sample Event',
  eventDate: { $currentDate: { $type: 'date' } },
});

Querying Dates

To query documents based on date values, you can perform comparisons using various query operators such as $lt, $lte, $gt, $gte, and $eq. Here are some examples:

// Find events that are happening before a certain date
const filterDate = new Date('2021-12-31');
db.events.find({ eventDate: { $lt: filterDate } });

// Find events that are happening after a certain date
const filterDate = new Date('2022-01-01');
db.events.find({ eventDate: { $gt: filterDate } });

Date Aggregations

MongoDB also provides aggregation functions for working with date values. Some common operations include $year, $month, $dayOfMonth, $hour, and $minute.

Example using the $dayOfYear and $year operators:

db.events.aggregate([
  {
    $group: {
      _id: {
        year: { $year: '$eventDate' },
        day: { $dayOfYear: '$eventDate' },
      },
      count: { $sum: 1 },
    },
  },
]);

This query groups events by the day and year, providing a count of events for each day.

Community

roadmap.sh is the 6th most starred project on GitHub and is visited by hundreds of thousands of developers every month.

Roadmaps Best Practices Guides Videos Store YouTube

roadmap.sh by Kamran Ahmed

Community created roadmaps, articles, resources and journeys to help you choose your path and grow in your career.

© roadmap.sh · FAQs · Terms · Privacy

ThewNewStack

The leading DevOps resource for Kubernetes, cloud-native computing, and the latest in at-scale development, deployment, and management.