Sling Academy
Home/MongoDB/MongoDB Date data type: A practical guide (with examples)

MongoDB Date data type: A practical guide (with examples)

Last updated: February 01, 2024

Introduction

MongoDB, a leading NoSQL database, provides flexible data structures, one of them being the Date data type. In this tutorial, we’ll explore how MongoDB handles dates, along with practical examples and some advanced operations to improve your date data handling skills.

Understanding the MongoDB Date type

The MongoDB Date type is used to store the current date or time in UTC by default. This BSON (Binary JSON) data type provides a straightforward way to work with dates and times, allowing for precision up to milliseconds. To create a new Date object in MongoDB, you can use the Date() function or the ISODate() factory function, which is more specific to MongoDB and ensures the date is stored in ISO format.

db.collection.insert({
    event: 'Sample Event',
    date: new Date()
})

After inserting the document, the date field will store the exact date and time of the insertion.

Querying Date Fields

Once you have date data in your collection, you might need to query it. Here’s a quick look:

db.collection.find({
    date: { $gt: new Date('2022-01-01') }
})

This query retrieves all documents with a date greater than January 1, 2022.

Advanced Date Queries

The true potential of date handling with MongoDB shows up in its powerful querying capabilities. For example, to find all documents from the previous week:

const lastWeek = new Date(new Date() - 604800000);
db.collection.find({
    date: { $gte: lastWeek }
})

Specifying precise date ranges or querying parts of the date, like hours or minutes, requires the aggregation framework’s date operators. Let’s say we want to find all events that start at 10am.

db.collection.aggregate([
    { 
        $project: {
            year: { $year: '$date' },
            month: { $month: '$date' },
            day: { $dayOfMonth: '$date' },
            hour: { $hour: '$date' }
        }
    },
    { 
        $match: {
            hour: 10
        }
    }
])

Here we utilized the $project stage to extract parts of the date, followed by the $match stage to filter by hour.

Indexing Date Fields

When dealing with large collections, indexing the date fields can significantly improve query performance. A single field index on the date field could look like this:

db.collection.createIndex({ 
   date: 1 
})

Once indexed, your queries concerning the date field will be much faster.

Working with Date in Aggregation

The aggregation pipeline in MongoDB can do complex date manipulations like grouping by date intervals. Below is an example aggregating sales by month.

db.sales.aggregate([
    { 
        $group: {
            _id: { $month: '$date' },
            totalSales: { $sum: '$amount' }
        }
    }
])

This will output the total sales for each month contained in your collection of sales.

Dealing with Timezones

Working with different time zones is a common issue. MongoDB, by default, stores dates in UTC, but it allows conversions using the aggregation pipeline. Here’s an example converting UTC dates to a specific timezone.

db.collection.aggregate([
    { 
        $addFields: {
            localDate: {
                $toDate: {
                    $subtract: [
                        { $toLong: '$date' }, 
                        (your timezone offset in milliseconds)
                    ]
                }
            }
        }
    }
])

This converts the UTC date field to your local timezone considering the provided offset.

Conclusion

In this tutorial, we have covered the basics of the MongoDB Date data type, showed how to query and manipulate date fields, deal with indexing, work with timezones, and perform aggregations based on date fields. Mastering these operations will significantly enhance your ability to manage and analyze time-based data within your MongoDB applications.

Next Article: MongoDB Int32 and Long data types: A practical guide (with examples)

Previous Article: Understanding ObjectId data type in MongoDB (with examples)

Series: MongoDB Tutorials

MongoDB

You May Also Like

  • MongoDB: How to combine data from 2 collections into one
  • Hashed Indexes in MongoDB: A Practical Guide
  • Partitioning and Sharding in MongoDB: A Practical Guide (with Examples)
  • Geospatial Indexes in MongoDB: How to Speed Up Geospatial Queries
  • Understanding Partial Indexes in MongoDB
  • Exploring Sparse Indexes in MongoDB (with Examples)
  • Using Wildcard Indexes in MongoDB: An In-Depth Guide
  • Matching binary values in MongoDB: A practical guide (with examples)
  • Understanding $slice operator in MongoDB (with examples)
  • Caching in MongoDB: A practical guide (with examples)
  • CannotReuseObject Error: Attempted illegal reuse of a Mongo object in the same process space
  • How to perform cascade deletion in MongoDB (with examples)
  • MongoDB: Using $not and $nor operators to negate a query
  • MongoDB: Find SUM/MIN/MAX/AVG of each group in a collection
  • References (Manual Linking) in MongoDB: A Developer’s Guide (with Examples)
  • MongoDB: How to see all fields in a collection (with examples)
  • Type checking in MongoDB: A practical guide (with examples)
  • How to query an array of subdocuments in MongoDB (with examples)
  • MongoDB: How to compare 2 documents (with examples)