17

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

Neil Lunn
  • 140,271
  • 35
  • 313
  • 302
itaied
  • 6,407
  • 13
  • 48
  • 72

3 Answers3

24

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.

Neil Lunn
  • 140,271
  • 35
  • 313
  • 302
  • 1
    This takes the date from the current working machine. Let's say the mongo is running on another server, and there is a small time differential, I want to display the date in the other machine, so I could see the difference even if it's a minute or so – itaied Jun 30 '14 at 06:21
  • @Candroid You really should be making sure the times are synchronized, but there is a way to use the server time. – Neil Lunn Jun 30 '14 at 06:35
10

You can do it trying something like this:

db.example.insert({"date":ISODate("2016-03-03T08:00:00.000")});
maikelsperandio
  • 171
  • 1
  • 6
2

Use this:

db.example.insert({"date":new Date(Date.now())});
Devesh Kumar
  • 979
  • 1
  • 16
  • 28