How to convert date to timestamp in MongoDB

To convert date to timestamp in MongoDB, use the $toLong operator within an aggregation pipeline. This converts an ISODate object to its Unix timestamp representation in milliseconds.

Syntax

db.collection.aggregate([
    {
        $addFields: {
            "timestampField": { $toLong: "$dateField" }
        }
    }
]);

Sample Data

db.demo93.insertMany([
    {"UserName": "Chris", "ArrivalDate": new ISODate("2020-10-01")},
    {"UserName": "David", "ArrivalDate": new ISODate("2019-12-31")}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e2d4b6479799acab037af68"),
        ObjectId("5e2d4b7379799acab037af69")
    ]
}

Display all documents to verify the data ?

db.demo93.find();
{ "_id": ObjectId("5e2d4b6479799acab037af68"), "UserName": "Chris", "ArrivalDate": ISODate("2020-10-01T00:00:00Z") }
{ "_id": ObjectId("5e2d4b7379799acab037af69"), "UserName": "David", "ArrivalDate": ISODate("2019-12-31T00:00:00Z") }

Example: Convert Date to Timestamp

Convert Chris's arrival date to timestamp ?

db.demo93.aggregate([
    { "$match": { "UserName": "Chris" }},
    { "$addFields": {
        "timestamp": { "$toLong": "$ArrivalDate" }
    }}
]);
{ "_id": ObjectId("5e2d4b6479799acab037af68"), "UserName": "Chris", "ArrivalDate": ISODate("2020-10-01T00:00:00Z"), "timestamp": NumberLong("1601510400000") }

Key Points

  • $toLong converts ISODate objects to Unix timestamps in milliseconds.
  • Use $addFields to add the timestamp without modifying existing fields.
  • The resulting timestamp is a NumberLong value representing milliseconds since epoch.

Conclusion

Use $toLong in aggregation pipelines to convert MongoDB ISODate fields to Unix timestamps. This is useful for date comparisons and integration with systems that expect numeric timestamps.

Updated on: 2026-03-15T01:53:42+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements