How to insert a document with date in mongo?

The standard driver takes java.util.date types and serializes as BSON dates. So with a collection object to “example”

Date now = new Date();

BasicDBObject timeNow = new BasicDBObject("date", now);
example.insert(timeNow);

If 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:

 BasicDBObject query = new BasicDBObect();
 BasicDBObject update = new BasicDBObject("$currentDate",
     new BasicDBObject("date", true)
 );

 example.update(query,update,true,false);

Since 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.

Leave a Comment