1

I need to insert the Mongo Date while inserting record to the collection in JAVA. I have used the document object for inserting data. Also used mongo-java-driver library for mongo connectivity. Is there any existing function to insert the mongo date (UTC date)?

Please check with the below code set

MongoDatabase database = mongoClient.getDatabase(dbName);
        MongoCollection<Document> collection = database.getCollection(collectionName);

Document document = new Document("key1", value1).append("key2", value2).append("key3", value3).append("date", new MongoDate());

collection.insertOne(document);  
Hari
  • 44
  • 9
  • 1
    Anything that returns a `java.util.Date` type really You can use that directly but probably with deprecation warnings. There are plenty of options but that is the basic type that the driver is looking for. I prefer [Joda Time](http://www.joda.org/joda-time/) – Neil Lunn May 30 '17 at 06:56
  • Is there any inbuilt functions inside java mongo driver to insert the date in UTC format? because i need to store UTC time without converting local time to UTC – Hari May 30 '17 at 06:59
  • Umm. `java.util.Date` is "built in" to Java. That's the point here. Also there are other libraries for handling dates. The MongoDB driver does not need to do any special manipulation, so it just uses the standard. – Neil Lunn May 30 '17 at 07:01
  • We can directly use the Java.util libraries Date function to add the UTC date in mongoDB. MongoDB normally convert this date to UTC Date while insert. Ex : MongoDatabase database = mongoClient.getDatabase(dbName); MongoCollection collection = database.getCollection(CollectionName); Document document = new Document("key1", val1).append("key2", val2) .append("key3", val3).append("created_date", new Date()); collection.insertOne(document); – Hari May 30 '17 at 09:45

0 Answers0