How to save Timestamp type value in MongoDb | Java

泪湿孤枕 提交于 2019-12-10 12:58:07

问题


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

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

Options I tried.

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

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

It results in the below not required format

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

Option 2:

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

it results in :

{"ts" : ISODate("2015-01-12T05:36:43.343Z")}

回答1:


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 the MongoDB result for a find is:

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

So the Serialisation of BSONTimeStamp to the classname and the Class attributes an their values depends on the spring-data-mongodb serializer. You should use the default java-mongodb-driver or use Java Date and the ISODate Format in MongoDB.

Or Maybe you could extend the spring-data-mongodb serializer and Write your own serializer and deserializer for the Class BSONTimeStamp to use the MongoDB Timestamp type.




回答2:


From MongoDB they recommend storing a Date since BSON Timestamp is for internal use:

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

The difference is that Date has more representation range since is a 64-bit integer that represents the number of milliseconds since Unix epoch.

In BSON Timestamp only 32 bits have this purpose; the other 32 bits are an incremental ordinal integer within a second to assure uniqueness of the value. I suppose this is the reason why they use Timestamp in oplog.

If you don't mind uniqueness I recommend to use a Date (aka ISODate), so option 2 or option 3:

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


来源:https://stackoverflow.com/questions/27895955/how-to-save-timestamp-type-value-in-mongodb-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!