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
How to convert from string to date data type in MongoDB?
To convert from string to date data type in MongoDB, you can use the ISODate() function within a script that iterates through documents and updates them. This is useful when you have date fields stored as strings that need to be converted to proper date objects.
Syntax
db.collection.find().forEach(function(doc){
doc.dateField = ISODate(doc.dateField);
db.collection.save(doc);
});
Create Sample Data
Let us first create a collection with documents containing string date values ?
db.stringToDateDataTypeDemo.insertMany([
{"CustomerName": "Carol", "ShippingDate": "2019-01-21"},
{"CustomerName": "Bob", "ShippingDate": "2019-02-24"},
{"CustomerName": "Chris", "ShippingDate": "2019-04-01"}
]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5ca2071d66324ffac2a7dc60"),
ObjectId("5ca2073566324ffac2a7dc61"),
ObjectId("5ca2074266324ffac2a7dc62")
]
}
Display Original Data
db.stringToDateDataTypeDemo.find().pretty();
{
"_id" : ObjectId("5ca2071d66324ffac2a7dc60"),
"CustomerName" : "Carol",
"ShippingDate" : "2019-01-21"
}
{
"_id" : ObjectId("5ca2073566324ffac2a7dc61"),
"CustomerName" : "Bob",
"ShippingDate" : "2019-02-24"
}
{
"_id" : ObjectId("5ca2074266324ffac2a7dc62"),
"CustomerName" : "Chris",
"ShippingDate" : "2019-04-01"
}
Convert String to Date
Use the following script to convert string dates to proper date objects ?
db.stringToDateDataTypeDemo.find().forEach(function(data){
data.ShippingDate = ISODate(data.ShippingDate);
db.stringToDateDataTypeDemo.save(data);
});
Verify Result
Display all documents to confirm the conversion ?
db.stringToDateDataTypeDemo.find().pretty();
{
"_id" : ObjectId("5ca2071d66324ffac2a7dc60"),
"CustomerName" : "Carol",
"ShippingDate" : ISODate("2019-01-21T00:00:00Z")
}
{
"_id" : ObjectId("5ca2073566324ffac2a7dc61"),
"CustomerName" : "Bob",
"ShippingDate" : ISODate("2019-02-24T00:00:00Z")
}
{
"_id" : ObjectId("5ca2074266324ffac2a7dc62"),
"CustomerName" : "Chris",
"ShippingDate" : ISODate("2019-04-01T00:00:00Z")
}
Conclusion
The ISODate() function successfully converts string dates to MongoDB date objects. Use forEach() to iterate through documents and save() to persist the changes with proper date data types.
Advertisements
