mongodb 时间戳 java,如何在MongoDb中保存时间戳类型值爪哇

本文探讨了如何使用默认MongoDB Java驱动正确保存BSONTimestamp到MongoDB,避免格式问题。作者提供了Option1和Option2的尝试,最后推荐使用DBObject和BSONTimeStamp构造,以保持与MongoDB预期的Timestamp格式一致。
摘要由CSDN通过智能技术生成

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")}

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值