
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert Date to Timestamp in MongoDB
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") }
Advertisements