How to convert date to timestamp in MongoDB

MongoDBDatabaseBig Data Analytics

To convert date to timestamp in MongoDB, use aggregate(). Let us create a collection with documents −

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

Display all documents from a collection with the help of find() method −

> db.demo93.find();

This will produce the following output −

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

Following is the query to convert date to timestamp in MongoDB −

> db.demo93.aggregate([
...    { "$match": { "UserName": "Chris" }},
...    { "$addFields": {
...       "timestamp": { "$toLong": "$ArrivalDate" }
...    }}
... ]);

This will produce the following output −

{ "_id" : ObjectId("5e2d4b6479799acab037af68"), "UserName" : "Chris", "ArrivalDate" : ISODate("2020-10-01T00:00:00Z"), "timestamp" : NumberLong("1601510400000") }
raja
Published on 30-Mar-2020 09:28:10
Advertisements