Re: Storing date field from JSON to MongoDB using Java API

929 views
Skip to first unread message

Stephen Lee

unread,
Oct 19, 2012, 9:55:57 AM10/19/12
to mongod...@googlegroups.com
You probably want to use something like Java's SimpleDateFormat class to first convert the (JSON) String to a Java Date, which should save as a ISODate in MongoDB.

On Thursday, October 18, 2012 6:08:58 PM UTC-4, Balaji Raghothaman wrote:
Hi,

I am using java api for mongodb to parse the JSON string into Java object and storing it into MongoDB.

My JSON string will have fields that are date like the one given below.
"created":"2012-10-17 21:39:06.385987 +0000"

When I try to save the parsed java object into MongoDB it stores the value as String. I would like to store it has a datetime field. Can someone shed some light on this?

Thanks and Regards,
Balaji.R

Balaji Raghothaman

unread,
Oct 19, 2012, 12:39:23 PM10/19/12
to mongod...@googlegroups.com
Hi Stephen,

Thanks for your response. Is there a way to dynamically convert all the values which are in a specific date format in the JSON string to Date object while parsing the JSON string to java object?

Thanks and Regards,
Balaji.R

Stephen Lee

unread,
Oct 19, 2012, 1:12:27 PM10/19/12
to mongod...@googlegroups.com
Balaji,

If you look at http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html, you can specify any date format, for example the JSON one, and automatically convert the JSON String to Java Date object, which in turn should automatically convert back a BSON date when you insert or update a document containing that value.

I hope that answers your question, but if that's still unclear, please let me know.

-Stephen
Reply all
Reply to author
Forward
0 new messages