- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB – Fix “Failed to convert from type String to type Date”?
To fix this, use $dateFromString in MongoDB aggregate(). The $dateFromString converts a date/time string to a date object.
Let us create a collection with documents −
> db.demo619.insertOne({"DueDate":"10-10-2020"}); { "acknowledged" : true, "insertedId" : ObjectId("5e99d7846c954c74be91e69e") } > db.demo619.insertOne({"DueDate":"12-01-2019"}); { "acknowledged" : true, "insertedId" : ObjectId("5e99d7996c954c74be91e69f") } > db.demo619.insertOne({"DueDate":"28-10-2010"}); { "acknowledged" : true, "insertedId" : ObjectId("5e99d7ab6c954c74be91e6a0") }
Display all documents from a collection with the help of find() method −
> db.demo619.find();
This will produce the following output −
{ "_id" : ObjectId("5e99d7846c954c74be91e69e"), "DueDate" : "10-10-2020" } { "_id" : ObjectId("5e99d7996c954c74be91e69f"), "DueDate" : "12-01-2019" } { "_id" : ObjectId("5e99d7ab6c954c74be91e6a0"), "DueDate" : "28-10-2010" }
Following is the query to convert from ty date/time string to a date object −
> db.demo619.aggregate( [ { ... $project: { ... DueDate: { ... $dateFromString: { ... dateString: '$DueDate', ... timezone: 'America/New_York' ... } ... } ... } ... } ] )
This will produce the following output −
{ "_id" : ObjectId("5e99d7846c954c74be91e69e"), "DueDate" : ISODate("2020-10-10T04:00:00Z") } { "_id" : ObjectId("5e99d7996c954c74be91e69f"), "DueDate" : ISODate("2019-01-12T05:00:00Z") } { "_id" : ObjectId("5e99d7ab6c954c74be91e6a0"), "DueDate" : ISODate("2010-10-28T04:00:00Z") }
Advertisements
To Continue Learning Please Login
Login with Google