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
MongoDB – Fix "Failed to convert from type String to type Date"?
To fix the "Failed to convert from type String to type Date" error in MongoDB, use $dateFromString in an aggregation pipeline. This operator converts a date/time string to a proper Date object that MongoDB can process.
Syntax
db.collection.aggregate([
{
$project: {
fieldName: {
$dateFromString: {
dateString: "$stringDateField",
format: "%d-%m-%Y",
timezone: "UTC"
}
}
}
}
])
Sample Data
db.demo619.insertMany([
{"DueDate": "10-10-2020"},
{"DueDate": "12-01-2019"},
{"DueDate": "28-10-2010"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e99d7846c954c74be91e69e"),
ObjectId("5e99d7996c954c74be91e69f"),
ObjectId("5e99d7ab6c954c74be91e6a0")
]
}
Display all documents from the collection ?
db.demo619.find();
{ "_id": ObjectId("5e99d7846c954c74be91e69e"), "DueDate": "10-10-2020" }
{ "_id": ObjectId("5e99d7996c954c74be91e69f"), "DueDate": "12-01-2019" }
{ "_id": ObjectId("5e99d7ab6c954c74be91e6a0"), "DueDate": "28-10-2010" }
Example: Convert String to Date
Convert the string dates to proper Date objects using $dateFromString ?
db.demo619.aggregate([
{
$project: {
DueDate: {
$dateFromString: {
dateString: '$DueDate',
timezone: 'America/New_York'
}
}
}
}
]);
{ "_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") }
Key Points
-
$dateFromStringautomatically detects common date formats like "MM-dd-yyyy". - Use the
formatparameter to specify custom date formats if needed. - The
timezoneparameter handles timezone conversion during parsing.
Conclusion
The $dateFromString operator in MongoDB aggregation pipelines effectively converts string representations of dates into proper Date objects, resolving type conversion errors. This ensures your date operations work correctly with proper Date types.
Advertisements
