简体   繁体   中英

How to insert a MongoDB document with a timestamp from the database server

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?

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM