Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
-
$toLongconverts ISODate objects to Unix timestamps in milliseconds. - Use
$addFieldsto 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.
Advertisements
