In MongoDB, I have a document with a field called "ClockInTime"
that was imported from CSV as a string.
What does an appropriate db.ClockTime.update()
statement look like to convert these text based values to a date datatype?
Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.
You can change the data type of a field by using the data type selectors on the right of the field in the Atlas Cloud Cluster as well as MongoDB Compass . If you want to update it using Mongo shell or any specific drivers of MongoDB then you can refer to the $convert operator.
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
The recommended way to store dates in MongoDB is to use the BSON Date data type. , which was 00:00:00 UTC on 1 January 1970. This provides a lot of flexibilty in past and future dates. With a 64-bit integer in use, we are able to represent dates roughly 290 million years before and after the epoch.
This code should do it:
> var cursor = db.ClockTime.find() > while (cursor.hasNext()) { ... var doc = cursor.next(); ... db.ClockTime.update({_id : doc._id}, {$set : {ClockInTime : new Date(doc.ClockInTime)}}) ... }
I have exactly the same situation as Jeff Fritz.
In my case I have succeed with the following simpler solution:
db.ClockTime.find().forEach(function(doc) { doc.ClockInTime=new Date(doc.ClockInTime); db.ClockTime.save(doc); })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With