Eyal Roth
Eyal Roth

Reputation: 4019

How to update a MongoDB from Java with the current DB time?

I want to update a mongo DB from my Java application with the current DB time (not the JVM's time).

If I had a shell, I would execute the following command:

db.colletion.update({_id : 'doc'}, {$set : { last_update : ISODate()}}, true, false);

I'm not sure how to translate it to java:

Object lastUpdate = ???;
DBObject q = new BasicDBObject("_id", "doc");
DBObject o = new BasicDBObject("$set", new BasicDBObject("last_update", lastUpdate));
collection.update(q, o, true, false);

I'm trying to figure out what should be lastUpdate object.

A new Date instance is not an option, because it will represent the JVM's time and not the DB's time.
I thought about using eval to get the time from the DB, but that will cost an extra query for each update.
Any other ideas?

Upvotes: 1

Views: 261

Answers (2)

jyemin
jyemin

Reputation: 3813

The next release of MongoDB (2.6) supports the $currentDate update operator. See http://docs.mongodb.org/master/release-notes/2.6/#write-operation-improvements for details.

Upvotes: 2

mnemosyn
mnemosyn

Reputation: 46281

The only way to do this is to use eval. From the eval documentation:

If you want to use the server’s interpreter, you must run eval. Otherwise, the mongo shell’s JavaScript interpreter evaluates functions entered directly into the shell.

even the command that you posted will use the client's time, not the server time, because the ISODate constructor will be evaluated on the client / shell.

Upvotes: 1

Related Questions