How to save a value of type Timestamp in MongoDb | Java

From the Java driver, I want to save a document that looks like json in MongoDb

{ "ts" : Timestamp(1421006159, 4)} 

Parameters I tried.

Option 1: Map doc = new HashMap (1);

 doc.put("ts", new BSONTimeStamp()); 

The result is the required format below.

 {"ts" : { "_inc" : 0, "_class" : "org.bson.types.BSONTimestamp" }} 

Option 2:

 doc.put("ts",new Timestamp(new Date().getTime())); 

This leads to:

 {"ts" : ISODate("2015-01-12T05:36:43.343Z")} 
+8
java spring-data-mongodb mongodb bson
source share
2 answers

I used the following with the default mongodb-java-driver (no spring) data.

 DBObject doc= new BasicDBObject(); doc.put("ts", new BSONTimeStamp(1421006159, 4)); 

And MongoDB result for search:

 { "_id" : ObjectId("54b396da7fe45ee2d6c5e03a"), "ts" : Timestamp(1421006159, 4) } 

Thus, BSONTimeStamp serialization for the class name and class attributes, their values ​​depend on the spring -data-mongodb serializer. You should use the default java-mongodb driver or use the Java Date and ISODate Format in MongoDB.

Or maybe you can extend the spring -data-mongodb serializer and write your own serializer and deserializer for the BSONTimeStamp class to use the Timestamp MongoDB type.

+4
source share

From MongoDB, they recommend storing the date, as the BSON timestamp is for internal use:

http://docs.mongodb.org/manual/reference/bson-types/#timestamps

The difference is that Date has a larger representation range because it is a 64-bit integer that represents the number of milliseconds since the Unix era.

In BSEC Timestamp, only 32 bits have this purpose; the remaining 32 bits are an incremental ordinal integer for a second to ensure value uniqueness. I guess that’s why they use Timestamp in oplog.

If you do not mind uniqueness, I recommend using Date (aka ISODate), so option 2 or option 3:

 doc.put("ts", new Date()); 
+4
source share

All Articles