12

In Oracle, I could simply do this:

INSERT INTO myTable VALUES ('someValue',SYSTIMESTAMP);

That would insert two values into myTable, and one of them would be a timestamp based-on the database server's time.

For MongoDB (via the Java driver) I've tried this:

myDoc.put("value","someValue");
myDoc.put("timestamp", new Date());
myCollection.insert(myDoc);

But that creates a timestamp based-on the client machine's time, not the database server's time.

Is there a way to have MongoDB apply a timestamp to a document based-on the the database server time?

Aaron
  • 55,518
  • 11
  • 116
  • 132

3 Answers3

8

A little late to the game - but the recent releases of mongodb have $currentDate.

See http://docs.mongodb.org/manual/reference/operator/update/currentDate/

Shane Gannon
  • 6,770
  • 7
  • 41
  • 64
0

Looks like you can get the server to generate a Timestamp on insert with db.test.insertOne( { ts: new Timestamp() } );. https://docs.mongodb.com/manual/reference/bson-types/#timestamps

k force
  • 153
  • 1
  • 7
-1

Use Morphia ORM tool for MongoDB

and for your problem hope lifecycle method of this is helpful.

i have getting result by using @Prepersist method

Yogesh Prajapati
  • 4,770
  • 2
  • 36
  • 77