Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a property in MongoDB from text to date type?

Tags:

mongodb

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?

like image 520
Jeff Fritz Avatar asked May 24 '10 22:05

Jeff Fritz


People also ask

How do I convert a string to a date?

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.

How do I change the datatype of a field in MongoDB?

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.

How does MongoDB write dates?

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.

What data type does MongoDB use for storing dates?

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.


2 Answers

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)}}) ... } 
like image 101
kristina Avatar answered Oct 24 '22 06:10

kristina


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);      }) 
like image 23
Ciges Avatar answered Oct 24 '22 08:10

Ciges