$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[June 08, 2026] MongoDB

MongoDB DateTime Handling

MongoDB DateTime Handling

────────────────────────────────────────────────────────

MongoDB DateTime Handling

Tip: Store as ISODate

['created_at' => new MongoDB\BSON\UTCDateTime(time() * 1000)]

Gotcha: UTC Only

MongoDB stores dates in UTC. Convert to local timezone in the application layer.

Tip: Date Aggregation

['$group' => [
    '_id' => ['$dateToString' => ['format' => '%Y-%m-%d', 'date' => '$created_at']],
    'count' => ['$sum' => 1],
]]

Gotcha: Milliseconds

UTCDateTime stores milliseconds. PHP time() returns seconds. Multiply by 1000.

Tip: Date Range Query

$collection->find([
    'created_at' => [
        '$gte' => new UTCDateTime(strtotime('2024-01-01') * 1000),
        '$lt' => new UTCDateTime(strtotime('2025-01-01') * 1000),
    ],
]);

Gotcha: String Dates

Don't store dates as strings. You lose date functions and sorting.

Tip: Embed or Reference? The 80/20 Rule

If you always access data together, embed it. If you access it independently, reference it. The 16MB document size limit is the hard boundary — stay under 1MB for most documents.

Tip: Index Your Query Patterns, Not All Fields

Creating indexes on every field wastes RAM. Use explain() to find in-memory sorts and collection scans. Index only what your actual queries filter on.

Gotcha: No Transaction Rollback for Index Builds

Building an index on a large collection can take hours. If it fails midway, the partial index is silently discarded. Plan index builds during maintenance windows.

Senior Insight

Date handling in MongoDB is straightforward: all Date types are stored in UTC. But I've seen applications store dates as strings in different formats ('2024-01-15', '01/15/2024', '15-01-2024'), making range queries impossible. Always use the BSON Date type (64-bit integer milliseconds since epoch) for date fields. MongoDB's aggregation pipeline has excellent date operators ($year, $month, $dayOfWeek, $dateToString), making time-series aggregation efficient.

Source: MongoDB Developer Center (https://www.mongodb.com/developer/), MongoDB Engineering Blog (https://www.mongodb.com/blog/channel/engineering-blog), Studio 3T Blog (https://studio3t.com/blog/)

────────────────────────────────────────────────────────
<-- back to posts