Home:ALL Converter>How to insert a document with date in mongo?

How to insert a document with date in mongo?

Ask Time:2014-06-30T13:58:59         Author:itaied

Json Formatter

We are trying to insert a document with the current date as it's field. We are writing in java using eclipse plugin for mongodb. We want to execute the Date() command of mongo to get the date from mongo and not from java.

How can I execute this mongo query?

db.example.insert({"date":new Date()})

I found this question in a previews question but the answer was not helpful

Link

Author:itaied,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/24483727/how-to-insert-a-document-with-date-in-mongo
Neil Lunn :

The standard driver takes java.util.date types and serializes as BSON dates. So with a collection object to \"example\"\n\nDate now = new Date();\n\nBasicDBObject timeNow = new BasicDBObject(\"date\", now);\nexample.insert(timeNow);\n\n\nIf you are looking for a way to use the \"server\" time in operations, there is the $currentDate operator, but this works with \"updates\", so you would want an \"upsert\" operation:\n\n BasicDBObject query = new BasicDBObect();\n BasicDBObject update = new BasicDBObject(\"$currentDate\",\n new BasicDBObject(\"date\", true)\n );\n\n example.update(query,update,true,false);\n\n\nSince that actually is an update statement, you need to be careful that you are not actually matching any documents if you intend this to be an insert only. So it would be best to make sure your \"query\" contains unique information, such as a newly generated _id or something equally unique.",
2014-06-30T06:14:49
maikelsperandio :

You can do it trying something like this:\n\ndb.example.insert({\"date\":ISODate(\"2016-03-03T08:00:00.000\")});\n",
2016-03-23T14:24:19
Devesh Kumar :

Use this:\n\ndb.example.insert({\"date\":new Date(Date.now())});\n",
2014-06-30T06:02:23
yy