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") }
Updated on: 2020-05-12T14:57:13+05:30

513 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements