Home:ALL Converter>How to insert date in mongo db from java

How to insert date in mongo db from java

Ask Time:2015-09-02T04:28:17         Author:juniorbansal

Json Formatter

There are many similar questions asked. But not exactly similar to the issue i am facing. I have seen almost all the questions and answers around it

So the problem is

I got to insert a date field in my mongo collection

But I can't access the collection directly. I got to use a service. The service takes a string and returns me oid.

So once i construct the BasicDBObject I call toString on it and pass it on to my service.. I even tried inserting it directly in a test collection and mongo is complaining.

 BasicDBObject document = new BasicDBObject(); 
    long createdAtSinceEpoch = 0;
    long expiresAtSinceEpoch = 0;

    createdAtSinceEpoch = System.nanoTime();
    Date createdAt = new Date(TimeUnit.NANOSECONDS.toMillis(createdAtSinceEpoch));
    document.append("createdAt", createdAt);

    expiresAtSinceEpoch = createdAtSinceEpoch + +TimeUnit.SECONDS.toNanos(30);
    Date expiresAt = new Date(TimeUnit.NANOSECONDS.toMillis(expiresAtSinceEpoch));
document.append("expiresAt", expiresAt);
service.storeRecord(document.toString());

and the generated JSON String looks like

{
"createdAt": {
    "$date": "2015-09-01T20:05:21.641Z"
},
"expiresAt": {
    "$date": "2015-09-01T20:05:51.641Z"
}

and Mongo complains that

Unable to parse JSON : Date expecting integer milliseconds, at (3,17)

So If i pass milliseconds alone instead of date object in the document.append() method then it DOES NOT recognize this field as date and considers it as String but inserts into the collection

I need 2 things

1) I want the data to be inserted 2) I am planning to expire that row by adding an index to the expiresAt field. So I want mongo to recognize that its a date field

Author:juniorbansal,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/32340329/how-to-insert-date-in-mongo-db-from-java
Bombe :

JSON makes a difference between a numeric field and a text field containing a number. The latter one is only recognized as a String; I assume that this is what you did when you thought you were giving your service the date as an integer. Unfortunately you didn’t show us the relevant code.",
2016-03-09T08:36:37
Srikanta :

When I save the Date info as a non String format, I annotate the field in my DTO as below. This helps the MongoDB know that the field is to be treated as an ISO date which then would be useful for making range search etc., \n\n@DateTimeFormat(iso = ISO.DATE_TIME) private Date date;\n",
2016-03-09T09:22:59
yy