Unix timestamps in MongoDB
A BSON Date is a 64-bit count of milliseconds since 1970 UTC, so converting to and from Unix milliseconds is lossless.
Get the current Unix timestamp
// mongosh
Date.now() // ms
Math.floor(Date.now() / 1000) // s
// In an aggregation pipeline the current time is "$$NOW"
Convert a Unix timestamp to a date
db.events.aggregate([
{ $set: { when: { $toDate: "$ts_ms" } } }, // milliseconds
{ $set: { when2: { $toDate: { $multiply: ["$ts_s", 1000] } } } } // seconds
])
Convert a date to a Unix timestamp
db.events.aggregate([
{ $set: { ts_ms: { $toLong: "$createdAt" } } },
{ $set: { ts_s: { $toLong: { $divide: [{ $toLong: "$createdAt" }, 1000] } } } }
])
Timezones
db.events.aggregate([
{ $project: { local: { $dateToString: {
date: "$createdAt", format: "%Y-%m-%d %H:%M:%S", timezone: "Asia/Kolkata" } } } }
])
Common mistakes
$toLongon a fractional result rounds toward zero. Use$floorbefore it for times before 1970.- The BSON
Timestamptype is for replication internals. Store application times asDate. - Every document's
_idalready holds its creation second:ObjectId(...).getTimestamp(). See ObjectId timestamp.
Complete example
// mongosh
db.demo.insertOne({ ts_s: 1700000000 })
db.demo.aggregate([
{ $set: { when: { $toDate: { $multiply: ["$ts_s", 1000] } } } },
{ $set: { back: { $toLong: { $divide: [{ $toLong: "$when" }, 1000] } } } }
])
Check any value with the epoch converter, or convert a whole column with the batch converter. All examples use 1700000000 (2023-11-14 22:13:20 UTC) and 1794650400 (2026-11-14 10:00:00 UTC).